Java Reference
In-Depth Information
6
7
public static void main(String[] args) throws IOException {
8
9
if (args.length != 1) // Test for correct argument list
10
throw new IllegalArgumentException("Parameter(s): <Port>");
11
12
int servPort = Integer.parseInt(args[0]);
13
14
DatagramSocket socket = new DatagramSocket(servPort);
15
DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
16
17
for (;;) { // Run forever, receiving and echoing datagrams
18
socket.receive(packet);
// Receive packet from client
19
System.out.println("Handling client at " +
20
packet.getAddress().getHostAddress()+"onport " + packet.getPort());
21
socket.send(packet);
// Send the same packet back to client
22
packet.setLength(ECHOMAX); // Reset length to avoid shrinking buffer
23
}
24
/* NOT REACHED */
25
}
26 }
UDPEchoServer.java
1. Application setup and parameter parsing: lines 0-12
UDPEchoServer takes a single parameter, the local port of the echo server socket.
2. Create and set up datagram socket: line 14
Unlike our UDP client, a UDP server must explicitly set its local port to a number known
by the client; otherwise, the client will not know the destination port for its echo request
datagram. When the server receives the echo datagram from the client, it can find out the
client's address and port from the datagram.
3. Create datagram: line 15
UDP messages are contained in datagrams. We construct an instance of DatagramPacket
with a buffer of
) bytes. This datagram will be used both to receive the echo
request and to send the echo reply.
echomax
(
255
4. Iteratively handle incoming echo requests: lines 17-23
The UDP server uses a single socket for all communication, unlike the TCP server, which
creates a new socket with every successful accept() .
Receive an echo request datagram: lines 18-20
The receive() method of DatagramSocket blocks until a datagram is received from a
client (unless a timeout is set). There is no connection, so each datagram may come
Search WWH ::




Custom Search