JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

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:

  • bind(): setting the server socket with the local system address, and a given local port number.
  • accept(): listening for a connection request, and instantiating a socket object when the request comes.

2. java.net.Socket with methods:

  • bind(): setting the socket with the local system address, and a given local port number.
  • connect(): sending a connection request to a given remote system address, and a given remote port number.

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: 2006.

Sections in This Chapter

What Is a Socket?

Establishing a Socket Communication Link

ReverseEchoer.java - A Simple Server Socket Application

SocketClient.java - A Simple Client Socket Application

ReverseEchoServer.java - A Multi-Connection Socket Server

Binding Sockets to Specific Ports

Dr. Herong Yang, updated in 2008
Establishing a Socket Communication Link