ServerSocket has a method called accept( ), which is a blocking call that will wait for a
client to initiate communications and then return with a normal Socket that is then used for
communication with the client.
TCP/IP-style networking is appropriate for most networking needs. It provides a serialized,
predictable, reliable stream of packet data. This is not without its cost, however. TCP
includes many complicated algorithms for dealing with congestion control on crowded
networks, as well as pessimistic expectations about packet loss. This leads to a somewhat
inefficient way to transport data. Datagrams provide an alternative.
Datagrams are bundles of information passed between machines. They are somewhat
like a hard throw from a well-trained but blindfolded catcher to the third baseman. Once
the datagram has been released to its intended target, there is no assurance that it will arrive
or even that someone will be there to catch it. Likewise, when the datagram is received,
there is no assurance that it hasn't been damaged in transit or that whoever sent it is still
there to receive a response.
Java implements datagrams on top of the UDP protocol by using two classes: the
DatagramPacket object is the data container, while the DatagramSocket is the mechanism
used to send or receive the DatagramPackets. Each is examined here.
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
DatagramSocket(int port, InetAddress ipAddress) throws SocketException
DatagramSocket(SocketAddress address) throws SocketException
The first creates a DatagramSocket bound to any unused port on the local computer. The
second creates a DatagramSocket bound to the port specified by port. The third constructs
a DatagramSocket bound to the specified port and InetAddress. The fourth constructs a
DatagramSocket bound to the specified SocketAddress. SocketAddress is an abstract
class that is implemented by the concrete class InetSocketAddress. InetSocketAddress
encapsulates an IP address with a port number. All can throw a SocketException if an error
occurs while creating the socket.
DatagramSocket defines many methods. Two of the most important are send( ) and
receive( ), which are shown here:
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
The send( ) method sends packet to the port specified by packet. The receive method waits
for a packet to be received from the port specified by packet and returns the result.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks