Package java.net |
![]() Previous |
![]() Java API |
![]() Index |
![]() Next |
public class java.net.DatagramSocket extends java.lang.Object { // Constructors public DatagramSocket(); public DatagramSocket(int port); // Methods public void close(); protected void finalize(); public int getLocalPort(); public void receive(DatagramPacket p); public void send(DatagramPacket p); }
This class represents a socket for sending and receiving datagram packets (Class DatagramPacket>).
A datagram socket is the sending or receiving point for a connectionless packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from a machine to another may be routed differently, and may arrive in any order.
public DatagramSocket()throws SocketExceptionConstructs a datagram socket and binds it to any available port on the local host machine.
Throw:
if the socket could not be opened, or the socket could not bind the specified local port.
public DatagramSocket(int port)throws SocketExceptionConstructs a datagram socket and binds it to the specified port on the local host machine.
Parameter Description local port to use Throw:
if the socket could not be opened, or the socket could not bind the specified local port.
public void close()Closes this datagram socket.
protected void finalize()Ensures that this socket is closed if there are no longer any references to this socket.
Overrides:
finalize in class Object .
public int getLocalPort()Return Value:
Returns the port number on the local host to which this socket is bound.
public void receive(DatagramPacket p)throws IOExceptionReceives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine.
This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the buffer length, the message is truncated.
Parameter Description p the DatagramPacket into which to place the incoming data Throw:
If an I/O error occurs.
public void send(DatagramPacket p)throws IOExceptionSends a datagram packet from this socket. The DatagramPacket includes information indicating the data to be sent, its length, the IP address of the remote host, and the port number on the remote host.
Parameter Description p the DatagramPacket to be sent Throw:
If an I/O error occurs.