Package java.net Previous
Previous
Java API
Java API
Index
Index
Next
Next

Class DatagramSocket

Constructors , Methods

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.


Constructors


DatagramSocket

public DatagramSocket() 
throws SocketException 

Constructs a datagram socket and binds it to any available port on the local host machine.

Throw:

SocketException

if the socket could not be opened, or the socket could not bind the specified local port.


DatagramSocket

public DatagramSocket(int  port) 
throws SocketException 

Constructs a datagram socket and binds it to the specified port on the local host machine.

ParameterDescription
local port to use

Throw:

SocketException

if the socket could not be opened, or the socket could not bind the specified local port.


Methods


close

public void close() 

Closes this datagram socket.


finalize

protected void finalize() 

Ensures that this socket is closed if there are no longer any references to this socket.

Overrides:

finalize in class Object .


getLocalPort

public int getLocalPort() 

Return Value:

Returns the port number on the local host to which this socket is bound.


receive

public void receive(DatagramPacket  p) 
throws IOException 

Receives 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.

ParameterDescription
p the DatagramPacket into which to place the incoming data

Throw:

IOException

If an I/O error occurs.


send

public void send(DatagramPacket  p) 
throws IOException 

Sends 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.

ParameterDescription
p the DatagramPacket to be sent

Throw:

IOException

If an I/O error occurs.



Top© 1996 Sun Microsystems, Inc. All rights reserved.