Network Programming with Java Sockets
The java.net package of the J2SE API contains a collection of classes and interfaces that provide the low-level communication details required for network programming. At the core of Java's networking support is the concept of a socket. A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. The socket associates the server program with a specific port on the machine and from where it runs any client program anywhere in the network. Sockets are at the foundation of modern networking because a socket allows a single computer (server) to serve many different clients at once as well as many different types of information. This is accomplished through the use of a port which is a numbered socket on a particular machine. A server is allowed to accept multiple clients connected to the same port number, though each session is unique. To manage multiple client connections a server must use multithreading. Although the java.net package provides support for both TCP/IP Sockets & Datagram Sockets, we will concentrate only on the TCP/IP Sockets as these are more widely used than the Datagram Sockets. A TCP/IP socket provides the communication mechanism between two computers using TCP. A client the program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object at the end of the communication. The client and the server can now communicate by writing to and reading from the socket. The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen to clients and establish connections with them.The following steps occur when establishing a TCP connection between two computers using sockets −
The server instantiates a ServerSocket object, denoting which port number communication is to occur on.The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.The constructor of the Socket class attempts to connect the client to the specified server and the port number.If communication is established, the client now has a Socket object capable of communicating with the server.On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.