Java Reference
In-Depth Information
public void bind(SocketAddress host, int backlog). Binds the socket to
the specified server and port in the SocketAddress object. Use this method
if you instantiated the ServerSocket using the no-argument constructor.
The accept() method is the one I want you to focus on because this is how
the server listens for incoming requests. When the ServerSocket invokes
accept(), the method does not return until a client connects (assuming that no
time-out value has been set). After a client does connect, the ServerSocket
creates a new Socket on an unspecified port (different from the port it was lis-
tening on) and returns a reference to this new Socket. A TCP connection now
exists between the client and server, and communication can begin.
If you are writing a server application that allows for multiple clients, you
want your server socket to always be invoking accept(), waiting for clients.
When a client does connect, the standard trick is to start a new thread for
communication with the new client, allowing the current thread to
immediately invoke accept() again. For example, if you have 50 clients
connected to a server, the server program will have 51 threads: 50 for
communicating with the clients and one additional thread waiting for a
new client via the accept() method.
The following SimpleServer program is an example of a server application
that uses the ServerSocket class to listen for clients on a port number specified
by a command-line argument. Notice that the server doesn't do much with the
client, but the program demonstrates how a connection is made with a client.
The return value of accept() is a Socket, so I need to discuss the Socket class
before we can do anything exciting with the connection. Study the Simple-
Server program and try to determine what its output will be.
import java.net.*;
import java.io.*;
public class SimpleServer extends Thread
{
private ServerSocket serverSocket;
public SimpleServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
Search WWH ::




Custom Search