Java Reference
In-Depth Information
newest message it has already received, and the server will send only newer messages that have higher
numbers assigned. If no number is given, the server will just send the 10 most recent messages.
Thus, we can define the following behaviors for reading:
• Client—Sends a request of type GET .
• Server—First it sends a line containing the number that will be assigned to the next message.
Then, if the URL is of the form /?start= N , a list of all messages, starting with message
number N, is transmitted. For all other URLs, the last 10 messages are submitted. All items are
separated by a pair of carriage return and linefeed control characters ( \r\n ).
For submitting text, you will use the HTTP POST command with an identical URL, but you will also
send the nickname and the text in the body of the request. In return, the server sends the same content
as for the GET command:
• Client—Sends a request of type POST .
• Server—Sends the same reply as for the GET command. The text just sent by the client is
included in the list of messages. Thus, at least one message is sent.
J2SE Chat Server
Now that we have defined the communication protocol, we can start with implementing a
corresponding server.
The server depends on the java.io and java.net packages. It stores the number of the current
message, a buffer for text, and a J2SE server socket in member variables:
import java.io.*;
import java.net.*;
public class ChatServer {
int current = 0;
String [] lines = new String [256];
ServerSocket serverSocket;
The constructor of the server gets a port number as input and creates a corresponding server socket:
public ChatServer (int port) throws IOException {
serverSocket = new ServerSocket (port);
System.out.println ("Serving port: "+port);
}
The run() method of the server contains a loop that waits for incoming connections. When a request
is accepted, a buffered reader and a writer corresponding to input and output streams associated with
the connection are handed over to the handleRequest() method. Usually, the actual handling of
the request would be performed in a separate thread, enabling the server to handle new requests
immediately. However, in order to keep the server as simple as possible, you handle the request in the
current thread, blocking new requests for the corresponding amount of time:
public void run() {
while (true) {
try {
Socket socket = serverSocket.accept();
handleRequest (new BufferedReader
(new InputStreamReader (socket.getInputStream())),
new OutputStreamWriter
(socket.getOutputStream()));
Search WWH ::




Custom Search