Class Socket
- java.lang.Object
-
- java.net.Socket
-
- All Implemented Interfaces:
Closeable,AutoCloseable
- Direct Known Subclasses:
SSLSocket
public class Socket extends Object implements Closeable
Provides a client-side TCP socket.
-
-
Constructor Summary
Constructors Modifier Constructor Description Socket()Creates a new unconnected socket.Socket(String dstName, int dstPort)Creates a new streaming socket connected to the target host specified by the parametersdstNameanddstPort.Socket(String hostName, int port, boolean streaming)Deprecated.UseSocket(String, int)instead of this for streaming sockets or an appropriate constructor ofDatagramSocketfor UDP transport.Socket(String dstName, int dstPort, InetAddress localAddress, int localPort)Creates a new streaming socket connected to the target host specified by the parametersdstNameanddstPort.Socket(InetAddress dstAddress, int dstPort)Creates a new streaming socket connected to the target host specified by the parametersdstAddressanddstPort.Socket(InetAddress addr, int port, boolean streaming)Deprecated.UseSocket(InetAddress, int)instead of this for streaming sockets or an appropriate constructor ofDatagramSocketfor UDP transport.Socket(InetAddress dstAddress, int dstPort, InetAddress localAddress, int localPort)Creates a new streaming socket connected to the target host specified by the parametersdstAddressanddstPort.Socket(Proxy proxy)Creates a new unconnected socket using the given proxy type.protectedSocket(SocketImpl impl)Creates an unconnected socket with the given socket implementation.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidbind(SocketAddress localAddr)Binds this socket to the given local host address and port specified by the SocketAddresslocalAddr.voidclose()Closes the socket.voidconnect(SocketAddress remoteAddr)Connects this socket to the given remote host address and port specified by the SocketAddressremoteAddr.voidconnect(SocketAddress remoteAddr, int timeout)Connects this socket to the given remote host address and port specified by the SocketAddressremoteAddrwith the specified timeout.SocketChannelgetChannel()Returns this socket'sSocketChannel, if one exists.FileDescriptorgetFileDescriptor$()InetAddressgetInetAddress()Returns the IP address of the target host this socket is connected to, or null if this socket is not yet connected.InputStreamgetInputStream()Returns an input stream to read data from this socket.booleangetKeepAlive()Returns this socket'sSocketOptions.SO_KEEPALIVEsetting.InetAddressgetLocalAddress()Returns the local IP address this socket is bound to, or an address for whichInetAddress.isAnyLocalAddress()returns true if the socket is closed or unbound.intgetLocalPort()Returns the local port this socket is bound to, or -1 if the socket is unbound.SocketAddressgetLocalSocketAddress()Returns the local address and port of this socket as a SocketAddress or null if the socket has never been bound.booleangetOOBInline()Returns this socket'sSocketOptions.SO_OOBINLINEsetting.OutputStreamgetOutputStream()Returns an output stream to write data into this socket.intgetPort()Returns the port number of the target host this socket is connected to, or 0 if this socket is not yet connected.intgetReceiveBufferSize()Returns this socket'sreceive buffer size.SocketAddressgetRemoteSocketAddress()Returns the remote address and port of this socket as aSocketAddressor null if the socket is not connected.booleangetReuseAddress()Returns this socket'sSocketOptions.SO_REUSEADDRsetting.booleangetReusePort()Returns this socket'sSocketOptions.SO_REUSEADDRsetting.intgetSendBufferSize()Returns this socket'ssend buffer size.intgetSoLinger()Returns this socket'slingertimeout in seconds, or -1 for no linger (i.e.intgetSoTimeout()Returns this socket'sreceive timeout.booleangetTcpNoDelay()Returns this socket'sSocketOptions#TCP_NODELAYsetting.intgetTrafficClass()Returns this socket's {@see SocketOptions#IP_TOS} setting.booleanisBound()Returns whether this socket is bound to a local address and port.booleanisClosed()Returns whether this socket is closed.booleanisConnected()Returns whether this socket is connected to a remote host.booleanisInputShutdown()Returns whether the incoming channel of the socket has already been closed.booleanisOutputShutdown()Returns whether the outgoing channel of the socket has already been closed.voidonBind(InetAddress localAddress, int localPort)Sets the Socket and its related SocketImpl state as if a successful bind() took place, without actually performing an OS bind().voidonClose()Sets the Socket and its related SocketImpl state as if a successful close() took place, without actually performing an OS close().voidonConnect(InetAddress remoteAddress, int remotePort)Sets the Socket and its related SocketImpl state as if a successful connect() took place, without actually performing an OS connect().voidsendUrgentData(int value)Sends the given single byte data which is represented by the lowest octet ofvalueas "TCP urgent data".voidsetKeepAlive(boolean keepAlive)Sets this socket'sSocketOptions.SO_KEEPALIVEoption.voidsetOOBInline(boolean oobinline)Sets this socket'sSocketOptions.SO_OOBINLINEoption.voidsetPerformancePreferences(int connectionTime, int latency, int bandwidth)Sets performance preferences for connectionTime, latency and bandwidth.voidsetReceiveBufferSize(int size)Sets this socket'sreceive buffer size.voidsetReuseAddress(boolean reuse)Sets this socket'sSocketOptions.SO_REUSEADDRoption.voidsetReusePort(boolean reuse)Sets this socket'sSocketOptions.SO_REUSEADDRoption.voidsetSendBufferSize(int size)Sets this socket'ssend buffer size.static voidsetSocketImplFactory(SocketImplFactory fac)Sets the internal factory for creating socket implementations.voidsetSoLinger(boolean on, int timeout)Sets this socket'slingertimeout in seconds.voidsetSoTimeout(int timeout)Sets this socket'sread timeoutin milliseconds.voidsetTcpNoDelay(boolean on)Sets this socket'sSocketOptions.TCP_NODELAYoption.voidsetTrafficClass(int value)Sets this socket'sSocketOptions.IP_TOSvalue for every packet sent by this socket.voidshutdownInput()Closes the input stream of this socket.voidshutdownOutput()Closes the output stream of this socket.StringtoString()Returns aStringcontaining a concise, human-readable description of the socket.
-
-
-
Constructor Detail
-
Socket
public Socket()
Creates a new unconnected socket. When a SocketImplFactory is defined it creates the internal socket implementation, otherwise the default socket implementation will be used for this socket.- See Also:
SocketImplFactory,SocketImpl
-
Socket
public Socket(Proxy proxy)
Creates a new unconnected socket using the given proxy type. When aSocketImplFactoryis defined it creates the internal socket implementation, otherwise the default socket implementation will be used for this socket.Example that will create a socket connection through a
SOCKSproxy server:
Socket sock = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("test.domain.org", 2130)));- Parameters:
proxy- the specified proxy for this socket.- Throws:
IllegalArgumentException- if the argumentproxyisnullor of an invalid type.- See Also:
SocketImplFactory,SocketImpl
-
Socket
public Socket(String dstName, int dstPort) throws UnknownHostException, IOException
Creates a new streaming socket connected to the target host specified by the parametersdstNameanddstPort. The socket is bound to any available port on the local host.This implementation tries each IP address for the given hostname (in RFC 3484 order) until it either connects successfully or it exhausts the set.
- Parameters:
dstName- the target host name or IP address to connect to.dstPort- the port on the target host to connect to.- Throws:
UnknownHostException- if the host name could not be resolved into an IP address.IOException- if an error occurs while creating the socket.
-
Socket
public Socket(String dstName, int dstPort, InetAddress localAddress, int localPort) throws IOException
Creates a new streaming socket connected to the target host specified by the parametersdstNameanddstPort. On the local endpoint the socket is bound to the given addresslocalAddresson portlocalPort. Ifhostisnulla loopback address is used to connect to.This implementation tries each IP address for the given hostname (in RFC 3484 order) until it either connects successfully or it exhausts the set.
- Parameters:
dstName- the target host name or IP address to connect to.dstPort- the port on the target host to connect to.localAddress- the address on the local host to bind to.localPort- the port on the local host to bind to.- Throws:
UnknownHostException- if the host name could not be resolved into an IP address.IOException- if an error occurs while creating the socket.
-
Socket
@Deprecated public Socket(String hostName, int port, boolean streaming) throws IOException
Deprecated.UseSocket(String, int)instead of this for streaming sockets or an appropriate constructor ofDatagramSocketfor UDP transport.Creates a new streaming or datagram socket connected to the target host specified by the parametershostNameandport. The socket is bound to any available port on the local host.This implementation tries each IP address for the given hostname (in RFC 3484 order) until it either connects successfully or it exhausts the set.
- Parameters:
hostName- the target host name or IP address to connect to.port- the port on the target host to connect to.streaming- iftruea streaming socket is returned, a datagram socket otherwise.- Throws:
UnknownHostException- if the host name could not be resolved into an IP address.IOException- if an error occurs while creating the socket.
-
Socket
public Socket(InetAddress dstAddress, int dstPort) throws IOException
Creates a new streaming socket connected to the target host specified by the parametersdstAddressanddstPort. The socket is bound to any available port on the local host using a wildcard address.- Parameters:
dstAddress- the target host address to connect to.dstPort- the port on the target host to connect to.- Throws:
IOException- if an error occurs while creating the socket.
-
Socket
public Socket(InetAddress dstAddress, int dstPort, InetAddress localAddress, int localPort) throws IOException
Creates a new streaming socket connected to the target host specified by the parametersdstAddressanddstPort.On the local endpoint the socket is bound to the given address
localAddresson portlocalPort. IflocalAddressisnullthe socket will be bound to a wildcard address.- Parameters:
dstAddress- the target host address to connect to.dstPort- the port on the target host to connect to.localAddress- the address on the local host to bind to, or null.localPort- the port on the local host to bind to.- Throws:
IOException- if an error occurs while creating the socket.
-
Socket
@Deprecated public Socket(InetAddress addr, int port, boolean streaming) throws IOException
Deprecated.UseSocket(InetAddress, int)instead of this for streaming sockets or an appropriate constructor ofDatagramSocketfor UDP transport.Creates a new streaming or datagram socket connected to the target host specified by the parametersaddrandport. The socket is bound to any available port on the local host using a wildcard address.- Parameters:
addr- the Internet address to connect to.port- the port on the target host to connect to.streaming- iftruea streaming socket is returned, a datagram socket otherwise.- Throws:
IOException- if an error occurs while creating the socket.
-
Socket
protected Socket(SocketImpl impl) throws SocketException
Creates an unconnected socket with the given socket implementation.- Parameters:
impl- the socket implementation to be used.- Throws:
SocketException- if an error occurs while creating the socket.
-
-
Method Detail
-
close
public void close() throws IOExceptionCloses the socket. It is not possible to reconnect or rebind to this socket thereafter which means a new socket instance has to be created.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- if an error occurs while closing the socket.
-
onClose
public void onClose()
Sets the Socket and its related SocketImpl state as if a successful close() took place, without actually performing an OS close().
-
getInetAddress
public InetAddress getInetAddress()
Returns the IP address of the target host this socket is connected to, or null if this socket is not yet connected.
-
getInputStream
public InputStream getInputStream() throws IOException
Returns an input stream to read data from this socket. If the socket has an associatedSocketChanneland that channel is in non-blocking mode then reads from the stream will throw aIllegalBlockingModeException.- Returns:
- the byte-oriented input stream.
- Throws:
IOException- if an error occurs while creating the input stream or the socket is in an invalid state.
-
getKeepAlive
public boolean getKeepAlive() throws SocketExceptionReturns this socket'sSocketOptions.SO_KEEPALIVEsetting.- Throws:
SocketException
-
getLocalAddress
public InetAddress getLocalAddress()
Returns the local IP address this socket is bound to, or an address for whichInetAddress.isAnyLocalAddress()returns true if the socket is closed or unbound.
-
getLocalPort
public int getLocalPort()
Returns the local port this socket is bound to, or -1 if the socket is unbound. If the socket has been closed this method will still return the local port the socket was bound to.
-
getOutputStream
public OutputStream getOutputStream() throws IOException
Returns an output stream to write data into this socket. If the socket has an associatedSocketChanneland that channel is in non-blocking mode then writes to the stream will throw aIllegalBlockingModeException.- Returns:
- the byte-oriented output stream.
- Throws:
IOException- if an error occurs while creating the output stream or the socket is in an invalid state.
-
getPort
public int getPort()
Returns the port number of the target host this socket is connected to, or 0 if this socket is not yet connected.
-
getSoLinger
public int getSoLinger() throws SocketExceptionReturns this socket'slingertimeout in seconds, or -1 for no linger (i.e.closewill return immediately).- Throws:
SocketException
-
getReceiveBufferSize
public int getReceiveBufferSize() throws SocketExceptionReturns this socket'sreceive buffer size.- Throws:
SocketException
-
getSendBufferSize
public int getSendBufferSize() throws SocketExceptionReturns this socket'ssend buffer size.- Throws:
SocketException
-
getSoTimeout
public int getSoTimeout() throws SocketExceptionReturns this socket'sreceive timeout.- Throws:
SocketException
-
getTcpNoDelay
public boolean getTcpNoDelay() throws SocketExceptionReturns this socket'sSocketOptions#TCP_NODELAYsetting.- Throws:
SocketException
-
setKeepAlive
public void setKeepAlive(boolean keepAlive) throws SocketExceptionSets this socket'sSocketOptions.SO_KEEPALIVEoption.- Throws:
SocketException
-
setSocketImplFactory
public static void setSocketImplFactory(SocketImplFactory fac) throws IOException
Sets the internal factory for creating socket implementations. This may only be executed once during the lifetime of the application.- Parameters:
fac- the socket implementation factory to be set.- Throws:
IOException- if the factory has been already set.
-
setSendBufferSize
public void setSendBufferSize(int size) throws SocketExceptionSets this socket'ssend buffer size.- Throws:
SocketException
-
setReceiveBufferSize
public void setReceiveBufferSize(int size) throws SocketExceptionSets this socket'sreceive buffer size.- Throws:
SocketException
-
setSoLinger
public void setSoLinger(boolean on, int timeout) throws SocketException- Throws:
SocketException
-
setSoTimeout
public void setSoTimeout(int timeout) throws SocketExceptionSets this socket'sread timeoutin milliseconds. Use 0 for no timeout. To take effect, this option must be set before the blocking method was called.- Throws:
SocketException
-
setTcpNoDelay
public void setTcpNoDelay(boolean on) throws SocketExceptionSets this socket'sSocketOptions.TCP_NODELAYoption.- Throws:
SocketException
-
toString
public String toString()
Returns aStringcontaining a concise, human-readable description of the socket.
-
shutdownInput
public void shutdownInput() throws IOExceptionCloses the input stream of this socket. Any further data sent to this socket will be discarded. Reading from this socket after this method has been called will return the valueEOF.- Throws:
IOException- if an error occurs while closing the socket input stream.SocketException- if the input stream is already closed.
-
shutdownOutput
public void shutdownOutput() throws IOExceptionCloses the output stream of this socket. All buffered data will be sent followed by the termination sequence. Writing to the closed output stream will cause anIOException.- Throws:
IOException- if an error occurs while closing the socket output stream.SocketException- if the output stream is already closed.
-
getLocalSocketAddress
public SocketAddress getLocalSocketAddress()
Returns the local address and port of this socket as a SocketAddress or null if the socket has never been bound. If the socket is closed but has previously been bound then an address for whichInetAddress.isAnyLocalAddress()returns true will be returned with the previously-bound port. This is useful on multihomed hosts.
-
getRemoteSocketAddress
public SocketAddress getRemoteSocketAddress()
Returns the remote address and port of this socket as aSocketAddressor null if the socket is not connected.- Returns:
- the remote socket address and port.
-
isBound
public boolean isBound()
Returns whether this socket is bound to a local address and port.- Returns:
trueif the socket is bound to a local address,falseotherwise.
-
isConnected
public boolean isConnected()
Returns whether this socket is connected to a remote host.- Returns:
trueif the socket is connected,falseotherwise.
-
isClosed
public boolean isClosed()
Returns whether this socket is closed.- Returns:
trueif the socket is closed,falseotherwise.
-
bind
public void bind(SocketAddress localAddr) throws IOException
Binds this socket to the given local host address and port specified by the SocketAddresslocalAddr. IflocalAddris set tonull, this socket will be bound to an available local address on any free port.- Parameters:
localAddr- the specific address and port on the local machine to bind to.- Throws:
IllegalArgumentException- if the given SocketAddress is invalid or not supported.IOException- if the socket is already bound or an error occurs while binding.
-
onBind
public void onBind(InetAddress localAddress, int localPort)
Sets the Socket and its related SocketImpl state as if a successful bind() took place, without actually performing an OS bind().
-
connect
public void connect(SocketAddress remoteAddr) throws IOException
Connects this socket to the given remote host address and port specified by the SocketAddressremoteAddr.- Parameters:
remoteAddr- the address and port of the remote host to connect to.- Throws:
IllegalArgumentException- if the given SocketAddress is invalid or not supported.IOException- if the socket is already connected or an error occurs while connecting.
-
connect
public void connect(SocketAddress remoteAddr, int timeout) throws IOException
Connects this socket to the given remote host address and port specified by the SocketAddressremoteAddrwith the specified timeout. The connecting method will block until the connection is established or an error occurred.- Parameters:
remoteAddr- the address and port of the remote host to connect to.timeout- the timeout value in milliseconds or0for an infinite timeout.- Throws:
IllegalArgumentException- if the given SocketAddress is invalid or not supported or the timeout value is negative.IOException- if the socket is already connected or an error occurs while connecting.
-
onConnect
public void onConnect(InetAddress remoteAddress, int remotePort)
Sets the Socket and its related SocketImpl state as if a successful connect() took place, without actually performing an OS connect().
-
isInputShutdown
public boolean isInputShutdown()
Returns whether the incoming channel of the socket has already been closed.- Returns:
trueif reading from this socket is not possible anymore,falseotherwise.
-
isOutputShutdown
public boolean isOutputShutdown()
Returns whether the outgoing channel of the socket has already been closed.- Returns:
trueif writing to this socket is not possible anymore,falseotherwise.
-
setReuseAddress
public void setReuseAddress(boolean reuse) throws SocketExceptionSets this socket'sSocketOptions.SO_REUSEADDRoption.- Throws:
SocketException
-
getReuseAddress
public boolean getReuseAddress() throws SocketExceptionReturns this socket'sSocketOptions.SO_REUSEADDRsetting.- Throws:
SocketException
-
setReusePort
public void setReusePort(boolean reuse) throws SocketExceptionSets this socket'sSocketOptions.SO_REUSEADDRoption.- Throws:
SocketException
-
getReusePort
public boolean getReusePort() throws SocketExceptionReturns this socket'sSocketOptions.SO_REUSEADDRsetting.- Throws:
SocketException
-
setOOBInline
public void setOOBInline(boolean oobinline) throws SocketExceptionSets this socket'sSocketOptions.SO_OOBINLINEoption.- Throws:
SocketException
-
getOOBInline
public boolean getOOBInline() throws SocketExceptionReturns this socket'sSocketOptions.SO_OOBINLINEsetting.- Throws:
SocketException
-
setTrafficClass
public void setTrafficClass(int value) throws SocketExceptionSets this socket'sSocketOptions.IP_TOSvalue for every packet sent by this socket.- Throws:
SocketException
-
getTrafficClass
public int getTrafficClass() throws SocketExceptionReturns this socket's {@see SocketOptions#IP_TOS} setting.- Throws:
SocketException
-
sendUrgentData
public void sendUrgentData(int value) throws IOExceptionSends the given single byte data which is represented by the lowest octet ofvalueas "TCP urgent data".- Parameters:
value- the byte of urgent data to be sent.- Throws:
IOException- if an error occurs while sending urgent data.
-
getChannel
public SocketChannel getChannel()
Returns this socket'sSocketChannel, 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 byServerSocketChannel.accept()orSocketChannel.open().
-
getFileDescriptor$
public FileDescriptor getFileDescriptor$()
-
setPerformancePreferences
public void setPerformancePreferences(int connectionTime, int latency, int bandwidth)Sets performance preferences for connectionTime, latency and bandwidth.This method does currently nothing.
- Parameters:
connectionTime- the value representing the importance of a short connecting time.latency- the value representing the importance of low latency.bandwidth- the value representing the importance of high bandwidth.
-
-