JDK Tutorials - Herong's Tutorial Examples - Version 6.02, by Dr. Herong Yang
Establishing a Socket Communication Link
This section describes how to establish a socket communication link. A server application runs a socket in listen mode and a client application connects a client socket to the server socket.
In the previous section, we only discussed about how socket works with a communication link that has been established already. Now, let's see how two application programs can establish a communication link between the local socket and the remote socket.
To establish a communication link, one application program must act as a server, create a server socket with a given port number, and set the server socket in the listen mode waiting for a connection request from other program.
With one program running as a server listening for a connection request at a specific port number, the other program can now create a client socket with a given local port number, the Internet address of the computer system where the first program is running, and the port number where the server socket is listening. At this time, a connect request will be send over to the server socket. The server socket should then accept the connect request and instantiate a socket object to complete communication link.
J2SDK offers two main classes to support socket communication:
1. java.net.ServerSocket with methods:
2. java.net.Socket with methods:
The following diagram shows steps involved in establishing a two-way communication link using the methods provided by ServerSocket and Socket classes:
Client System Server System Internet Address #a Internet Address #b Step Available Port #p Available Port #q 1 ss = new ServerSocket() 2 ss.bind(#b+#q) 3 Socket cs = ss.accept() 4 cs = new Socket() (waiting) 5 cs.bind(#a+#p) (waiting) 6 cs.connect(#b+#q) (receiving request) 7 (estalishing the link) (establishing the link) 8 (cs is ready) (cs is ready)
Last update: 2014.
Table of Contents