Java Reference
In-Depth Information
int getSoTimeout ()
void setSoTimeout ( int timeout )
Returns/sets the maximum amount of time that a receive() will block for this socket.
If the specified time elapses before data is available, an InterruptedIOException is
thrown.
timeout
The maximum amount of time (milliseconds) that receive()
will block for the socket. A timeout of 0 indicates that a
receive will block until data is available.
2.3.3 UDP Server
Like a TCP server, a UDP server's job is to set up a communication endpoint and passively
wait for the client to initiate the communication; however, since UDP is connectionless, UDP
communication is initiated by a datagram from the client, without going through a connection
setup as in TCP. The typical UDP server goes through four steps:
1. Construct an instance of DatagramSocket , specifying the local port and, optionally, the
local address. The server is now ready to receive datagrams from any client.
2. Receive an instance of DatagramPacket using the receive() method of DatagramSocket .
When receive() returns, the datagram contains the client's address so we know where
to send the reply.
3. Communicate by sending and receiving DatagramPackets using the send() and receive()
methods of DatagramSocket .
4. When finished, deallocate the socket using the close() method of DatagramSocket .
Our next program example, UDPEchoServer.java , implements the UDP version of the echo
server. The server is very simple: it loops forever, receiving datagrams and then sending the
same datagrams back to the client. Actually, our server only receives and sends back the first
255 ( echomax ) characters of the datagram; any excess is silently discarded by the socket
implementation (see Section 2.3.4).
UDPEchoServer.java
0 import java.net.*; // for DatagramSocket, DatagramPacket, and InetAddress
1 import java.io.*;
// for IOException
2
3 public class UDPEchoServer {
4
5
private static final int ECHOMAX = 255; // Maximum size of echo datagram
Search WWH ::




Custom Search