Class Socket
- java.lang.Object
-
- java.net.Socket
-
- All Implemented Interfaces:
Closeable,AutoCloseable
- Direct Known Subclasses:
SSLSocket
public class Socket extends Object implements Closeable
This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.- Since:
- JDK1.0
-
-
Constructor Summary
Constructors Constructor Description Socket()Creates an unconnected socket, with the system-default type of SocketImpl.Socket(String host, int port)Creates a stream socket and connects it to the specified port number on the named host.Socket(String host, int port, InetAddress localAddr, int localPort)Creates a socket and connects it to the specified remote host on the specified remote port.Socket(InetAddress address, int port)Creates a stream socket and connects it to the specified port number at the specified IP address.Socket(InetAddress address, int port, InetAddress localAddr, int localPort)Creates a socket and connects it to the specified remote address on the specified remote port.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidbind(SocketAddress bindpoint)Binds the socket to a local address.voidclose()Closes this socket.voidconnect(SocketAddress endpoint)Connects this socket to the server.voidconnect(SocketAddress endpoint, int timeout)Connects this socket to the server with a specified timeout value.InetAddressgetInetAddress()Returns the address to which the socket is connected.InputStreamgetInputStream()Returns an input stream for this socket.booleangetKeepAlive()Tests ifSO_KEEPALIVEis enabled.InetAddressgetLocalAddress()Gets the local address to which the socket is bound.intgetLocalPort()Returns the local port number to which this socket is bound.SocketAddressgetLocalSocketAddress()Returns the address of the endpoint this socket is bound to.booleangetOOBInline()Tests ifSO_OOBINLINEis enabled.OutputStreamgetOutputStream()Returns an output stream for this socket.intgetPort()Returns the remote port number to which this socket is connected.intgetReceiveBufferSize()Gets the value of theSO_RCVBUFoption for thisSocket, that is the buffer size used by the platform for input on thisSocket.SocketAddressgetRemoteSocketAddress()Returns the address of the endpoint this socket is connected to, ornullif it is unconnected.booleangetReuseAddress()Tests ifSO_REUSEADDRis enabled.intgetSendBufferSize()Get value of theSO_SNDBUFoption for thisSocket, that is the buffer size used by the platform for output on thisSocket.intgetSoLinger()Returns setting forSO_LINGER.intgetSoTimeout()Returns setting forSO_TIMEOUT.booleangetTcpNoDelay()Tests ifTCP_NODELAYis enabled.intgetTrafficClass()Gets traffic class or type-of-service in the IP header for packets sent from this SocketbooleanisBound()Returns the binding state of the socket.booleanisClosed()Returns the closed state of the socket.booleanisConnected()Returns the connection state of the socket.voidsetKeepAlive(boolean on)Enable/disableSO_KEEPALIVE.voidsetOOBInline(boolean on)Enable/disableSO_OOBINLINE(receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded.voidsetReceiveBufferSize(int size)Sets theSO_RCVBUFoption to the specified value for thisSocket.voidsetReuseAddress(boolean on)Enable/disable theSO_REUSEADDRsocket option.voidsetSendBufferSize(int size)Sets theSO_SNDBUFoption to the specified value for thisSocket.voidsetSoLinger(boolean on, int linger)Enable/disableSO_LINGERwith the specified linger time in seconds.voidsetSoTimeout(int timeout)Enable/disableSO_TIMEOUTwith the specified timeout, in milliseconds.voidsetTcpNoDelay(boolean on)Enable/disableTCP_NODELAY(disable/enable Nagle's algorithm).voidsetTrafficClass(int tc)Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.StringtoString()Converts this socket to aString.
-
-
-
Constructor Detail
-
Socket
public Socket()
Creates an unconnected socket, with the system-default type of SocketImpl.- Since:
- JDK1.1
-
Socket
public Socket(@Nullable String host, int port) throws UnknownHostException, IOException
Creates a stream socket and connects it to the specified port number on the named host.If the specified host is
nullit is the equivalent of specifying the address asInetAddress.getByName(null). In other words, it is equivalent to specifying an address of the loopback interface.If the application has specified a server socket factory, that factory's
createSocketImplmethod is called to create the actual socket implementation. Otherwise a "plain" socket is created.If there is a security manager, its
checkConnectmethod is called with the host address andportas its arguments. This could result in a SecurityException.- Parameters:
host- the host name, ornullfor the loopback address.port- the port number.- Throws:
UnknownHostException- if the IP address of the host could not be determined.IOException- if an I/O error occurs when creating the socket.SecurityException- if a security manager exists and itscheckConnectmethod doesn't allow the operation.IllegalArgumentException- if the port parameter is outside the specified range of valid port values, which is between 0 and 65535, inclusive.
-
Socket
public Socket(InetAddress address, int port) throws IOException
Creates a stream socket and connects it to the specified port number at the specified IP address.If the application has specified a socket factory, that factory's
createSocketImplmethod is called to create the actual socket implementation. Otherwise a "plain" socket is created.If there is a security manager, its
checkConnectmethod is called with the host address andportas its arguments. This could result in a SecurityException.- Parameters:
address- the IP address.port- the port number.- Throws:
IOException- if an I/O error occurs when creating the socket.SecurityException- if a security manager exists and itscheckConnectmethod doesn't allow the operation.IllegalArgumentException- if the port parameter is outside the specified range of valid port values, which is between 0 and 65535, inclusive.NullPointerException- ifaddressis null.
-
Socket
public Socket(@Nullable String host, int port, @Nullable InetAddress localAddr, int localPort) throws IOException
Creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.If the specified host is
nullit is the equivalent of specifying the address asInetAddress.getByName(null). In other words, it is equivalent to specifying an address of the loopback interface.A local port number of
zerowill let the system pick up a free port in thebindoperation.If there is a security manager, its
checkConnectmethod is called with the host address andportas its arguments. This could result in a SecurityException.- Parameters:
host- the name of the remote host, ornullfor the loopback address.port- the remote portlocalAddr- the local address the socket is bound to, ornullfor theanyLocaladdress.localPort- the local port the socket is bound to, orzerofor a system selected free port.- Throws:
IOException- if an I/O error occurs when creating the socket.SecurityException- if a security manager exists and itscheckConnectmethod doesn't allow the connection to the destination, or if itscheckListenmethod doesn't allow the bind to the local port.IllegalArgumentException- if the port parameter or localPort parameter is outside the specified range of valid port values, which is between 0 and 65535, inclusive.- Since:
- JDK1.1
-
Socket
public Socket(InetAddress address, int port, @Nullable InetAddress localAddr, int localPort) throws IOException
Creates a socket and connects it to the specified remote address on the specified remote port. The Socket will also bind() to the local address and port supplied.If the specified local address is
nullit is the equivalent of specifying the address as the AnyLocal address (seeInetAddress.isAnyLocalAddress()).A local port number of
zerowill let the system pick up a free port in thebindoperation.If there is a security manager, its
checkConnectmethod is called with the host address andportas its arguments. This could result in a SecurityException.- Parameters:
address- the remote addressport- the remote portlocalAddr- the local address the socket is bound to, ornullfor theanyLocaladdress.localPort- the local port the socket is bound to orzerofor a system selected free port.- Throws:
IOException- if an I/O error occurs when creating the socket.SecurityException- if a security manager exists and itscheckConnectmethod doesn't allow the connection to the destination, or if itscheckListenmethod doesn't allow the bind to the local port.IllegalArgumentException- if the port parameter or localPort parameter is outside the specified range of valid port values, which is between 0 and 65535, inclusive.NullPointerException- ifaddressis null.- Since:
- JDK1.1
-
-
Method Detail
-
connect
public void connect(SocketAddress endpoint) throws IOException
Connects this socket to the server.- Parameters:
endpoint- theSocketAddress- Throws:
IOException- if an error occurs during the connectionIllegalArgumentException- if endpoint is null or is a SocketAddress subclass not supported by this socket- Since:
- 1.4
-
connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.- Parameters:
endpoint- theSocketAddresstimeout- the timeout value to be used in milliseconds.- Throws:
IOException- if an error occurs during the connectionSocketTimeoutException- if timeout expires before connectingIllegalArgumentException- if endpoint is null or is a SocketAddress subclass not supported by this socket- Since:
- 1.4
-
bind
public void bind(@Nullable SocketAddress bindpoint) throws IOException
Binds the socket to a local address.If the address is
null, then the system will pick up an ephemeral port and a valid local address to bind the socket.- Parameters:
bindpoint- theSocketAddressto bind to- Throws:
IOException- if the bind operation fails, or if the socket is already bound.IllegalArgumentException- if bindpoint is a SocketAddress subclass not supported by this socketSecurityException- if a security manager exists and itscheckListenmethod doesn't allow the bind to the local port.- Since:
- 1.4
- See Also:
isBound()
-
getInetAddress
@Nullable public InetAddress getInetAddress()
Returns the address to which the socket is connected.If the socket was connected prior to being
closed, then this method will continue to return the connected address after the socket is closed.- Returns:
- the remote IP address to which this socket is connected, or
nullif the socket is not connected.
-
getLocalAddress
public InetAddress getLocalAddress()
Gets the local address to which the socket is bound.If there is a security manager set, its
checkConnectmethod is called with the local address and-1as its arguments to see if the operation is allowed.- Returns:
- the local address to which the socket is bound, or the wildcard address if the socket is closed or not bound yet.
- Since:
- JDK1.1
-
getPort
public int getPort()
Returns the remote port number to which this socket is connected.If the socket was connected prior to being
closed, then this method will continue to return the connected port number after the socket is closed.- Returns:
- the remote port number to which this socket is connected, or 0 if the socket is not connected yet.
-
getLocalPort
public int getLocalPort()
Returns the local port number to which this socket is bound.If the socket was bound prior to being
closed, then this method will continue to return the local port number after the socket is closed.- Returns:
- the local port number to which this socket is bound or -1 if the socket is not bound yet.
-
getRemoteSocketAddress
@Nullable public SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, ornullif it is unconnected.If the socket was connected prior to being
closed, then this method will continue to return the connected address after the socket is closed.- Returns:
- a
SocketAddressrepresenting the remote endpoint of this socket, ornullif it is not connected yet. - Since:
- 1.4
- See Also:
getInetAddress(),getPort(),connect(SocketAddress, int),connect(SocketAddress)
-
getLocalSocketAddress
@Nullable public SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to.If a socket bound to an endpoint represented by an
InetSocketAddressisclosed, then this method will continue to return anInetSocketAddressafter the socket is closed. In that case the returnedInetSocketAddress's address is thewildcardaddress and its port is the local port that it was bound to.If there is a security manager set, its
checkConnectmethod is called with the local address and-1as its arguments to see if the operation is allowed.- Returns:
- a
SocketAddressrepresenting the local endpoint of this socket, ornullif the socket is not bound yet. - Since:
- 1.4
- See Also:
getLocalAddress(),getLocalPort(),bind(SocketAddress)
-
getInputStream
public InputStream getInputStream() throws IOException
Returns an input stream for this socket.Under abnormal conditions the underlying connection may be broken by the remote host or the network software (for example a connection reset in the case of TCP connections). When a broken connection is detected by the network software the following applies to the returned input stream :-
-
The network software may discard bytes that are buffered by the socket. Bytes that aren't discarded by the network software can be read using
read. -
If there are no bytes buffered on the socket, or all buffered bytes have been consumed by
read, then all subsequent calls toreadwill throw anIOException. -
If there are no bytes buffered on the socket, and the socket has not been closed using
close, thenavailablewill return0.
Closing the returned
InputStreamwill close the associated socket.- Returns:
- an input stream for reading bytes from this socket.
- Throws:
IOException- if an I/O error occurs when creating the input stream, the socket is closed or the socket is not connected.
-
-
getOutputStream
public OutputStream getOutputStream() throws IOException
Returns an output stream for this socket.Closing the returned
OutputStreamwill close the associated socket.- Returns:
- an output stream for writing bytes to this socket.
- Throws:
IOException- if an I/O error occurs when creating the output stream or if the socket is not connected.
-
setTcpNoDelay
public void setTcpNoDelay(boolean on) throws SocketExceptionEnable/disableTCP_NODELAY(disable/enable Nagle's algorithm).- Parameters:
on-trueto enable TCP_NODELAY,falseto disable.- Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- JDK1.1
- See Also:
getTcpNoDelay()
-
getTcpNoDelay
public boolean getTcpNoDelay() throws SocketExceptionTests ifTCP_NODELAYis enabled.- Returns:
- a
booleanindicating whether or notTCP_NODELAYis enabled. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- JDK1.1
- See Also:
setTcpNoDelay(boolean)
-
setSoLinger
public void setSoLinger(boolean on, int linger) throws SocketExceptionEnable/disableSO_LINGERwith the specified linger time in seconds. The maximum timeout value is platform specific. The setting only affects socket close.- Parameters:
on- whether or not to linger on.linger- how long to linger for, if on is true.- Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.IllegalArgumentException- if the linger value is negative.- Since:
- JDK1.1
- See Also:
getSoLinger()
-
getSoLinger
public int getSoLinger() throws SocketExceptionReturns setting forSO_LINGER. -1 returns implies that the option is disabled. The setting only affects socket close.- Returns:
- the setting for
SO_LINGER. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- JDK1.1
- See Also:
setSoLinger(boolean, int)
-
setOOBInline
public void setOOBInline(boolean on) throws SocketExceptionEnable/disableSO_OOBINLINE(receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. If the user wishes to receive urgent data, then this option must be enabled. When enabled, urgent data is received inline with normal data.Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.
- Parameters:
on-trueto enableSO_OOBINLINE,falseto disable.- Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.4
- See Also:
getOOBInline()
-
getOOBInline
public boolean getOOBInline() throws SocketExceptionTests ifSO_OOBINLINEis enabled.- Returns:
- a
booleanindicating whether or notSO_OOBINLINEis enabled. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.4
- See Also:
setOOBInline(boolean)
-
setSoTimeout
public void setSoTimeout(int timeout) throws SocketExceptionEnable/disableSO_TIMEOUTwith the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be> 0. A timeout of zero is interpreted as an infinite timeout.- Parameters:
timeout- the specified timeout, in milliseconds.- Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- JDK 1.1
- See Also:
getSoTimeout()
-
getSoTimeout
public int getSoTimeout() throws SocketExceptionReturns setting forSO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).- Returns:
- the setting for
SO_TIMEOUT - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- JDK1.1
- See Also:
setSoTimeout(int)
-
setSendBufferSize
public void setSendBufferSize(int size) throws SocketExceptionSets theSO_SNDBUFoption to the specified value for thisSocket. TheSO_SNDBUFoption is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.Because
SO_SNDBUFis a hint, applications that want to verify what size the buffers were set to should callgetSendBufferSize().- Parameters:
size- the size to which to set the send buffer size. This value must be greater than 0.- Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.IllegalArgumentException- if the value is 0 or is negative.- Since:
- 1.2
- See Also:
getSendBufferSize()
-
getSendBufferSize
public int getSendBufferSize() throws SocketExceptionGet value of theSO_SNDBUFoption for thisSocket, that is the buffer size used by the platform for output on thisSocket.- Returns:
- the value of the
SO_SNDBUFoption for thisSocket. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.2
- See Also:
setSendBufferSize(int)
-
setReceiveBufferSize
public void setReceiveBufferSize(int size) throws SocketExceptionSets theSO_RCVBUFoption to the specified value for thisSocket. TheSO_RCVBUFoption is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.
Because
SO_RCVBUFis a hint, applications that want to verify what size the buffers were set to should callgetReceiveBufferSize().The value of
SO_RCVBUFis also used to set the TCP receive window that is advertized to the remote peer. Generally, the window size can be modified at any time when a socket is connected. However, if a receive window larger than 64K is required then this must be requested before the socket is connected to the remote peer. There are two cases to be aware of:- For sockets accepted from a ServerSocket, this must be done by calling
ServerSocket.setReceiveBufferSize(int)before the ServerSocket is bound to a local address. - For client sockets, setReceiveBufferSize() must be called before connecting the socket to its remote peer.
- Parameters:
size- the size to which to set the receive buffer size. This value must be greater than 0.- Throws:
IllegalArgumentException- if the value is 0 or is negative.SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.2
- See Also:
getReceiveBufferSize(),ServerSocket.setReceiveBufferSize(int)
- For sockets accepted from a ServerSocket, this must be done by calling
-
getReceiveBufferSize
public int getReceiveBufferSize() throws SocketExceptionGets the value of theSO_RCVBUFoption for thisSocket, that is the buffer size used by the platform for input on thisSocket.- Returns:
- the value of the
SO_RCVBUFoption for thisSocket. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.2
- See Also:
setReceiveBufferSize(int)
-
setKeepAlive
public void setKeepAlive(boolean on) throws SocketExceptionEnable/disableSO_KEEPALIVE.- Parameters:
on- whether or not to have socket keep alive turned on.- Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.3
- See Also:
getKeepAlive()
-
getKeepAlive
public boolean getKeepAlive() throws SocketExceptionTests ifSO_KEEPALIVEis enabled.- Returns:
- a
booleanindicating whether or notSO_KEEPALIVEis enabled. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.3
- See Also:
setKeepAlive(boolean)
-
setTrafficClass
public void setTrafficClass(int tc) throws SocketExceptionSets traffic class or type-of-service octet in the IP header for packets sent from this Socket. As the underlying network implementation may ignore this value applications should consider it a hint.The tc must be in the range
0 <= tc <= 255or an IllegalArgumentException will be thrown.Notes:
For Internet Protocol v4 the value consists of an
integer, the least significant 8 bits of which represent the value of the TOS octet in IP packets sent by the socket. RFC 1349 defines the TOS values as follows:IPTOS_LOWCOST (0x02)IPTOS_RELIABILITY (0x04)IPTOS_THROUGHPUT (0x08)IPTOS_LOWDELAY (0x10)
Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.
As RFC 1122 section 4.2.4.2 indicates, a compliant TCP implementation should, but is not required to, let application change the TOS field during the lifetime of a connection. So whether the type-of-service field can be changed after the TCP connection has been established depends on the implementation in the underlying platform. Applications should not assume that they can change the TOS field after the connection.
For Internet Protocol v6
tcis the value that would be placed into the sin6_flowinfo field of the IP header.- Parameters:
tc- anintvalue for the bitset.- Throws:
SocketException- if there is an error setting the traffic class or type-of-service- Since:
- 1.4
- See Also:
getTrafficClass(),SocketOptions.IP_TOS
-
getTrafficClass
public int getTrafficClass() throws SocketExceptionGets traffic class or type-of-service in the IP header for packets sent from this SocketAs the underlying network implementation may ignore the traffic class or type-of-service set using
setTrafficClass(int)this method may return a different value than was previously set using thesetTrafficClass(int)method on this Socket.- Returns:
- the traffic class or type-of-service already set
- Throws:
SocketException- if there is an error obtaining the traffic class or type-of-service value.- Since:
- 1.4
- See Also:
setTrafficClass(int),SocketOptions.IP_TOS
-
setReuseAddress
public void setReuseAddress(boolean on) throws SocketExceptionEnable/disable theSO_REUSEADDRsocket option.When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the
TIME_WAITstate or2MSLwait state). For applications using a well known socket address or port it may not be possible to bind a socket to the requiredSocketAddressif there is a connection in the timeout state involving the socket address or port.Enabling
SO_REUSEADDRprior to binding the socket usingbind(SocketAddress)allows the socket to be bound even though a previous connection is in a timeout state.When a
Socketis created the initial setting ofSO_REUSEADDRis disabled.The behaviour when
SO_REUSEADDRis enabled or disabled after a socket is bound (SeeisBound()) is not defined.- Parameters:
on- whether to enable or disable the socket option- Throws:
SocketException- if an error occurs enabling or disabling theSO_REUSEADDRsocket option, or the socket is closed.- Since:
- 1.4
- See Also:
getReuseAddress(),bind(SocketAddress),isClosed(),isBound()
-
getReuseAddress
public boolean getReuseAddress() throws SocketExceptionTests ifSO_REUSEADDRis enabled.- Returns:
- a
booleanindicating whether or notSO_REUSEADDRis enabled. - Throws:
SocketException- if there is an error in the underlying protocol, such as a TCP error.- Since:
- 1.4
- See Also:
setReuseAddress(boolean)
-
close
public void close() throws IOExceptionCloses this socket.Any thread currently blocked in an I/O operation upon this socket will throw a
SocketException.Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.
Closing this socket will also close the socket's
InputStreamandOutputStream.If this socket has an associated channel then the channel is closed as well.
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- if an I/O error occurs when closing this socket.- See Also:
isClosed()
-
toString
public String toString()
Converts this socket to aString.
-
isConnected
public boolean isConnected()
Returns the connection state of the socket.Note: Closing a socket doesn't clear its connection state, which means this method will return
truefor a closed socket (seeisClosed()) if it was successfuly connected prior to being closed.- Returns:
- true if the socket was successfuly connected to a server
- Since:
- 1.4
-
isBound
public boolean isBound()
Returns the binding state of the socket.Note: Closing a socket doesn't clear its binding state, which means this method will return
truefor a closed socket (seeisClosed()) if it was successfuly bound prior to being closed.- Returns:
- true if the socket was successfuly bound to an address
- Since:
- 1.4
- See Also:
bind(java.net.SocketAddress)
-
isClosed
public boolean isClosed()
Returns the closed state of the socket.- Returns:
- true if the socket has been closed
- Since:
- 1.4
- See Also:
close()
-
-