Package java.net
Class DatagramSocket
java.lang.Object
java.net.DatagramSocket
- All Implemented Interfaces:
Closeable,AutoCloseable
- Direct Known Subclasses:
MulticastSocket
public class DatagramSocket extends Object implements Closeable
This class implements a UDP socket for sending and receiving
DatagramPacket. A DatagramSocket object can be used for both
endpoints of a connection for a packet delivery service.- See Also:
DatagramPacket,DatagramSocketImplFactory
-
Constructor Summary
Constructors Modifier Constructor Description DatagramSocket()Constructs a UDP datagram socket which is bound to any available port on the localhost.DatagramSocket(int aPort)Constructs a UDP datagram socket which is bound to the specific portaPorton the localhost.DatagramSocket(int aPort, InetAddress addr)Constructs a UDP datagram socket which is bound to the specific local addressaddron portaPort.protectedDatagramSocket(DatagramSocketImpl socketImpl)Constructs a newDatagramSocketusing the specific datagram socket implementationsocketImpl.DatagramSocket(SocketAddress localAddr)Constructs a newDatagramSocketbound to the host/port specified by theSocketAddresslocalAddror an unboundDatagramSocketif theSocketAddressisnull. -
Method Summary
Modifier and Type Method Description voidbind(SocketAddress localAddr)Binds this socket to the local address and port specified bylocalAddr.voidclose()Closes this UDP datagram socket and all possibly associated channels.voidconnect(InetAddress address, int port)Connects this datagram socket to the specificaddressandport.voidconnect(SocketAddress peer)Connects this datagram socket to the address and port specified bypeer.voiddisconnect()Disconnects this UDP datagram socket from the remote host.booleangetBroadcast()Gets the state of the socket optionSocketOptions.SO_BROADCAST.DatagramChannelgetChannel()Returns this socket'sDatagramChannel, if one exists.FileDescriptorgetFileDescriptor$()InetAddressgetInetAddress()Gets theInetAddressinstance representing the remote address to which this UDP datagram socket is connected.InetAddressgetLocalAddress()Returns the local address to which this socket is bound, ornullif this socket is closed.intgetLocalPort()Gets the local port which this socket is bound to.SocketAddressgetLocalSocketAddress()Returns theSocketAddressthis socket is bound to, or null for an unbound socket.intgetPort()Gets the remote port which this socket is connected to.intgetReceiveBufferSize()Returns this socket'sreceive buffer size.SocketAddressgetRemoteSocketAddress()Returns theSocketAddressthis socket is connected to, or null for an unconnected socket.booleangetReuseAddress()Gets the state of the socket optionSocketOptions.SO_REUSEADDR.intgetSendBufferSize()Returns this socket'ssend buffer size.intgetSoTimeout()Gets the socketreceive timeout.intgetTrafficClass()Returns this socket's {@see SocketOptions#IP_TOS} setting.booleanisBound()Returns true if this socket is bound to a local address.booleanisClosed()Gets the state of this socket.booleanisConnected()Returns true if this datagram socket is connected to a remote address.voidreceive(DatagramPacket pack)Receives a packet from this socket and stores it in the argumentpack.voidsend(DatagramPacket pack)Sends a packet over this socket.voidsetBroadcast(boolean broadcast)Sets the socket optionSocketOptions.SO_BROADCAST.static voidsetDatagramSocketImplFactory(DatagramSocketImplFactory fac)Sets the socket implementation factory.voidsetNetworkInterface(NetworkInterface netInterface)Sets the network interface used by this socket.voidsetReceiveBufferSize(int size)Sets this socket'sreceive buffer size.voidsetReuseAddress(boolean reuse)Sets the socket optionSocketOptions.SO_REUSEADDR.voidsetSendBufferSize(int size)Sets this socket'ssend buffer size.voidsetSoTimeout(int timeout)Sets theread timeoutin milliseconds for this socket.voidsetTrafficClass(int value)Sets the {@see SocketOptions#IP_TOS} value for every packet sent by this socket.
-
Constructor Details
-
DatagramSocket
Constructs a UDP datagram socket which is bound to any available port on the localhost.- Throws:
SocketException- if an error occurs while creating or binding the socket.
-
DatagramSocket
Constructs a UDP datagram socket which is bound to the specific portaPorton the localhost. Valid values foraPortare between 0 and 65535 inclusive.- Parameters:
aPort- the port to bind on the localhost.- Throws:
SocketException- if an error occurs while creating or binding the socket.
-
DatagramSocket
Constructs a UDP datagram socket which is bound to the specific local addressaddron portaPort. Valid values foraPortare between 0 and 65535 inclusive.- Parameters:
aPort- the port to bind on the localhost.addr- the address to bind on the localhost.- Throws:
SocketException- if an error occurs while creating or binding the socket.
-
DatagramSocket
Constructs a newDatagramSocketusing the specific datagram socket implementationsocketImpl. The createdDatagramSocketwill not be bound.- Parameters:
socketImpl- the DatagramSocketImpl to use.
-
DatagramSocket
Constructs a newDatagramSocketbound to the host/port specified by theSocketAddresslocalAddror an unboundDatagramSocketif theSocketAddressisnull.- Parameters:
localAddr- the local machine address and port to bind to.- Throws:
IllegalArgumentException- if the SocketAddress is not supportedSocketException- if a problem occurs creating or binding the socket.
-
-
Method Details
-
close
public void close()Closes this UDP datagram socket and all possibly associated channels.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
disconnect
public void disconnect()Disconnects this UDP datagram socket from the remote host. This method called on an unconnected socket does nothing. -
getInetAddress
Gets theInetAddressinstance representing the remote address to which this UDP datagram socket is connected.- Returns:
- the remote address this socket is connected to or
nullif this socket is not connected.
-
getLocalAddress
Returns the local address to which this socket is bound, ornullif this socket is closed. -
getLocalPort
public int getLocalPort()Gets the local port which this socket is bound to.- Returns:
- the local port of this socket or
-1if this socket is closed and0if it is unbound.
-
getPort
public int getPort()Gets the remote port which this socket is connected to.- Returns:
- the remote port of this socket. The return value
-1indicates that this socket is not connected.
-
getReceiveBufferSize
Returns this socket'sreceive buffer size.- Throws:
SocketException
-
getSendBufferSize
Returns this socket'ssend buffer size.- Throws:
SocketException
-
getSoTimeout
Gets the socketreceive timeout.- Throws:
SocketException- if an error occurs while getting the option value.
-
receive
Receives a packet from this socket and stores it in the argumentpack. All fields ofpackmust be set according to the data received. If the received data is longer than the packet buffer size it is truncated. This method blocks until a packet is received or a timeout has expired.- Parameters:
pack- theDatagramPacketto store the received data.- Throws:
IOException- if an error occurs while receiving the packet.
-
send
Sends a packet over this socket.- Parameters:
pack- theDatagramPacketwhich has to be sent.- Throws:
IOException- if an error occurs while sending the packet.
-
setNetworkInterface
Sets the network interface used by this socket. Any packets sent via this socket are transmitted via the specified interface. Any packets received by this socket will come from the specified interface. Broadcast datagrams received on this interface will be processed by this socket. This corresponds to Linux's SO_BINDTODEVICE.- Throws:
SocketException
-
setSendBufferSize
Sets this socket'ssend buffer size.- Throws:
SocketException
-
setReceiveBufferSize
Sets this socket'sreceive buffer size.- Throws:
SocketException
-
setSoTimeout
Sets theread timeoutin milliseconds for this socket. This receive timeout defines the period the socket will block waiting to receive data before throwing anInterruptedIOException. The value0(default) is used to set an infinite timeout. To have effect this option must be set before the blocking method was called.- Parameters:
timeout- the timeout in milliseconds or 0 for no timeout.- Throws:
SocketException- if an error occurs while setting the option.
-
setDatagramSocketImplFactory
Sets the socket implementation factory. This may only be invoked once over the lifetime of the application. This factory is used to create a new datagram socket implementation.- Parameters:
fac- the socket factory to use.- Throws:
IOException- if the factory has already been set.- See Also:
DatagramSocketImplFactory
-
bind
Binds this socket to the local address and port specified bylocalAddr. If this value isnullany free port on a valid local address is used.- Parameters:
localAddr- the local machine address and port to bind on.- Throws:
IllegalArgumentException- if the SocketAddress is not supportedSocketException- if the socket is already bound or a problem occurs during binding.
-
connect
Connects this datagram socket to the address and port specified bypeer. Future calls tosend(java.net.DatagramPacket)will use this as the default target, andreceive(java.net.DatagramPacket)will only accept packets from this source.- Throws:
SocketException- if an error occurs.
-
connect
Connects this datagram socket to the specificaddressandport. Future calls tosend(java.net.DatagramPacket)will use this as the default target, andreceive(java.net.DatagramPacket)will only accept packets from this source.Beware: because it can't throw, this method silently ignores failures. Use
connect(SocketAddress)instead. -
isBound
public boolean isBound()Returns true if this socket is bound to a local address. Seebind(java.net.SocketAddress). -
isConnected
public boolean isConnected()Returns true if this datagram socket is connected to a remote address. Seeconnect(java.net.SocketAddress). -
getRemoteSocketAddress
Returns theSocketAddressthis socket is connected to, or null for an unconnected socket. -
getLocalSocketAddress
Returns theSocketAddressthis socket is bound to, or null for an unbound socket. -
setReuseAddress
Sets the socket optionSocketOptions.SO_REUSEADDR. This option has to be enabled if more than one UDP socket wants to be bound to the same address. That could be needed for receiving multicast packets.There is an undefined behavior if this option is set after the socket is already bound.
- Parameters:
reuse- the socket option value to enable or disable this option.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getReuseAddress
Gets the state of the socket optionSocketOptions.SO_REUSEADDR.- Returns:
trueif the option is enabled,falseotherwise.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
setBroadcast
Sets the socket optionSocketOptions.SO_BROADCAST. This option must be enabled to send broadcast messages.- Parameters:
broadcast- the socket option value to enable or disable this option.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getBroadcast
Gets the state of the socket optionSocketOptions.SO_BROADCAST.- Returns:
trueif the option is enabled,falseotherwise.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
setTrafficClass
Sets the {@see SocketOptions#IP_TOS} value for every packet sent by this socket.- Throws:
SocketException- if the socket is closed or the option could not be set.
-
getTrafficClass
Returns this socket's {@see SocketOptions#IP_TOS} setting.- Throws:
SocketException- if the socket is closed or the option is invalid.
-
isClosed
public boolean isClosed()Gets the state of this socket.- Returns:
trueif the socket is closed,falseotherwise.
-
getChannel
Returns this socket'sDatagramChannel, if one exists. A channel is available only if this socket wraps a channel. (That is, you can go from a channel to a socket and back again, but you can't go from an arbitrary socket to a channel.) In practice, this means that the socket must have been created byDatagramChannel.open(). -
getFileDescriptor$
-