Java Reference
In-Depth Information
Sidebar 14.1 Sockets
Sockets are the standard tool used for communicating over a computer network. Sockets are a
flexible tool and support a large spectrum of communication protocols, the most common being
those in the TCP
IP framework.
We will focus on the TCP protocol. There are two classes that are used to establish and carry out
normal TCP connections:
ServerSocket
and
Socket
. For simple connections between a client and a
server they are likely to be sufficient.
ServerSocket
represents the socket on a server that waits and listens for requests for service from
a client.
Socket
represents the endpoints for communication between a server and a client. When
a server gets a request for service, it creates a
Socket
for communication with the client and
continues to listen for other requests on the
ServerSocket
. The client also creates a
Socket
for
communication with the server. The sequence is shown below in Figure 14.15 (from the Sun Java
Networking Overview).
Server application
network connection
new
Client Application
server : ServerSocket
new
client_side : Socket
accept()
connect
new
server_side : Socket
server_side
the accept() method
blocks the caller until
a connection has
been established
The two sockets are
now connected
Figure 14.15
Setup of a socket connection
Once the connection is established,
getInputStream()
and
getOutputSteam()
may be used in com-
munication between the sockets. A sample server program is the following:
ServerSocket server
#
new
ServerSocket(SERVER_PORT);
Socket socket
#
server.accept();
InputStream in
#
socket. getInputStream();
OutputStream out
#
socket. getOutputStream();