Java Reference
In-Depth Information
Caveat:
By default,
Socket
is implemented on top of a TCP connection; however, in Java,
you can actually change the underlying implementation of
Socket
. This topic is about TCP/IP,
so for simplicity we assume that the underlying implementation for all of the these networking
classes is the default.
2.2.2 TCP Server
We now turn our attention to constructing a server. The server's job is to set up a communi-
cation endpoint and passively wait for connections from clients. The typical TCP server goes
through two steps:
1. Construct a
ServerSocket
instance, specifying the local port. This socket listens for
incoming connections to the specified port.
2. Repeatedly:
Call the
accept()
method of
ServerSocket
to get the next incoming client connection.
Upon establishment of a new client connection, an instance of
Socket
for the new
connection is created and returned by
accept()
.
Communicate with the client using the returned
Socket
's
InputStream
and
Output−
Stream
.
Close the new client socket connection using the
close()
method of
Socket
.
Our next example,
TCPEchoServer.java
, implements the echo service used by our client
program. The server is very simple. It runs forever, repeatedly accepting a connection, receiving
and echoing bytes until the connection is closed by the client, and then closing the client socket.
TCPEchoServer.java
0
import java.net.*; // for Socket, ServerSocket, and InetAddress
1
import java.io.*;
// for IOException and Input/OutputStream
2
3
public class TCPEchoServer {
4
5
private static final int BUFSIZE = 32;
// Size of receive buffer
6
7
public static void main(String[] args) throws IOException {
8
9
if (args.length != 1) // Test for correct # of args
10
throw new IllegalArgumentException("Parameter(s): <Port>");
11
12
int servPort = Integer.parseInt(args[0]);
13
14
// Create a server socket to accept client connection requests
15
ServerSocket servSock = new ServerSocket(servPort);
16
17
int recvMsgSize;
// Size of received message
18
byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer
Search WWH ::
Custom Search