Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/sample/nio/chatserver/README.txt
38829 views
A Simple Chat Server Example12INTRODUCTION3============4This directory contains a very simple chat server, the server takes input from a5socket ("user") and sends it to all other connected sockets ("users") along with6the provided name the user was asked for when first connecting.78The server was written to demonstrate the asynchronous I/O API in JDK 7.9The sample assumes the reader has some familiarity with the subject matter.1011SETUP12=====1314The server must be built with version 7 (or later) of the JDK.15The server is built with:1617% mkdir build18% javac -source 7 -target 7 -d build *.java1920EXECUTION21=========2223% java -classpath build ChatServer [-port <port number>]2425Usage: ChatServer [options]26options:27-port port port number28default: 50002930CLIENT EXECUTION31================3233No client binary is included in the sample.34Connections can be made using for example the telnet command or any program35that supports a raw TCP connection to a port.3637SOURCE CODE OVERVIEW38====================39ChatServer is the main class, it handles the startup and handles incoming40connections on the listening sockets. It keeps a list of connected client41and provides methods for sending a message to them.4243Client represents a connected user, it provides methods for reading/writing44from/to the underlying socket. It also contains a buffer of input read from45the user.4647DataReader provides the interface of the two states a user can48be in. Waiting for a name (and not receiving any messages while doing so, implemented49by NameReader) and waiting for messages from the user (implemented by MessageReader).5051ClientReader contains the "main loop" for a connected client.5253NameReader is the initial state for a new client, it sends the user a string and54waits for a response before changing the state to MessageReader.5556MessageReader is the main state for a client, it checks for new messages to send to57other clients and reads messages from the client.5859FINALLY60=======61This is a sample: it is not production quality and isn't optimized for performance.626364