Server Socket

The ServerSocket class represents the server side of a client/server connection.  This special kind of socket typically idles, waiting for a request from a client.  Upon receiving the request, the ServerSocket spawns a regular Socket instance, performs the appropriate action and sends a reply to the client making the request.  As a result, a single ServerSocket can queue up and reply to several clients from different machines. 

The ServerSocket object should specify which port it will be listening on. It utilizes a method called accept() to wait for client requests. This method will return a Socket object when a request is made. As with the client side, output and input streams may be instantiated for communication with the client.

Here's a Server socket example:


import java.net.*;
import java.io.*;
import java.util.*;

public class ServerTest {

	ServerSocket ss;
	
	public static void main (String args[]) throws IOException {
		ServerTest st = new ServerTest();
		st.listen();
	}
	
	public void listen() throws IOException {
		Socket response;
		ss = new ServerSocket(6000, 5);
		while(true) 
		{
		response = ss.accept();
		OutputStream os = response.getOutputStream();
		BufferedWriter buf = new BufferedWriter(new 
				OutputStreamWriter(os));
		buf.write("It is: " + (new Date()).toString() + "\n");
		buf.close();
		response.close();
		}
	}
}

 

Next...                                                                                                                                page 11-8