O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Program: Chat Client

This program is a simple Chat program. You can’t break in on ICQ or AIM with it, because they each use their own protocol;[36] this one simply writes to and reads from a server, locating the server with the applet method getCodeBase( ). The server for this will be presented in Chapter 16. How does it look when you run it? Figure 15-2 shows me chatting all by myself one day.

Chat client in action

Figure 15-2. Chat client in action

The code is reasonably self-explanatory. We read from the remote server in a thread to make the input and the output run without blocking each other; this is discussed in Chapter 24. The reading and writing are discussed in this chapter. The program is an applet (see Section 17.3) and is shown in Example 15-11.

Example 15-11. ChatClient.java

import java.applet.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; /** Simple Chat Room Applet. * Writing a Chat Room seems to be one of many obligatory rites (or wrongs) * of passage for Java experts these days. * <P> * This one is a toy because it doesn't implement much of a command protocol, which * means we can't query the server as to * who's logged in, * or anything fancy like that. However, it works OK for small groups. * <P> * Uses client socket w/ two Threads (main and one constructed), * one for reading and one for writing. * <P> * Server multiplexes messages back to all clients. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required