Mega Code Archive

 
Categories / Java Book / 006 Networking
 

0372 DatagramSocket

Java implements datagrams on top of the UDP protocol by using two classes: DatagramPacket object is the data container DatagramSocket is the mechanism used to send or receive the DatagramPackets. DatagramSocket defines four public constructors. DatagramSocket( ) throws SocketException creates a DatagramSocket bound to any unused port on the local computer. DatagramSocket(int port) throws SocketException creates a DatagramSocket bound to the port specified by port. DatagramSocket(int port, InetAddress ipAddress) throws SocketException constructs a DatagramSocket bound to the specified port and InetAddress. DatagramSocket(SocketAddress address) throws SocketException 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. Two of the most important methods 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. Other methods defined: InetAddress getInetAddress( ) If the socket is connected, then the address is returned. Otherwise, null is returned. int getLocalPort( ) Returns the number of the local port. int getPort( ) Returns the number of the port to which the socket is connected. It returns -1 if the socket is not connected to a port. boolean isBound( ) Returns true if the socket is bound to an address. Returns false otherwise. boolean isConnected( ) Returns true if the socket is connected to a server. Returns false otherwise. void setSoTimeout(int millis) throws SocketException Sets the time-out period to the number of milliseconds passed in millis.