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.
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. ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.