Lesson 7: Sockets

Overview

The Socket class is the fundamental building block of client/server communication. A socket is an end-point of communication. The server listens on a created socket for connections from a client. The client creates it own socket and connects it to the waiting server socket. Once the connection is made, the InputStream and OutputStream is extracted from the Socket and is used for communication.

Examples

  1. WebClient.java
  2. TalkClient.java
  3. TalkServer.java

The details

Network communications is handled by the java.net package. A socket is an abstract software entity which represents the end-point of a communication and generally follows a TCP/IP model. A socket binds to an address and a port at that address. For example, the socket which handles Web serving for MIT is bound to address 18.69.0.38, port 80.

Server sockets bind passively and waits for connection requests. Client sockets actively seek out a companion socket to connect with. This is called the client/server architecture. Both client and server sockets have addresses and port numbers. The addresses locate the machine on the network. The port locates the application within the machine. Generally, the client port number is automatically assigned to any available port, the server port number is either well-known, such as 80 for Web serving, or is available through some sort of directory service.

Many layers of software are involved in establishing connections using sockets. Each layer can be implemented in a variety of ways, using a variety of vendors and technologies. These represent competing viewpoints on what services should be provided. The Internet can provides two classes of service. TCP/IP is a reliable stream service, UDP/IP is an unreliable packet service. Since the unreliablity of UDP introduces numerous error control and recovery issues, we will concentrate on TCP.

Once a TCP connection is established between client and server, a byte stream communication channel is supported. The InputStream and OutputStream object which represent the channel are available from the Socket object using getInputStream and getOutputStream. You use these as you would a byte stream from a file or from a keyboard. When done, use close to shut down communication.