Skip to content

Most visited

Recently visited

navigation
Added in API level 1

Socket

public class Socket
extends Object implements Closeable

java.lang.Object
   ↳ java.net.Socket
Known Direct Subclasses


Provides a client-side TCP socket.

Summary

Public constructors

Socket()

Creates a new unconnected socket.

Socket(Proxy proxy)

Creates a new unconnected socket using the given proxy type.

Socket(String dstName, int dstPort)

Creates a new streaming socket connected to the target host specified by the parameters dstName and dstPort.

Socket(String dstName, int dstPort, InetAddress localAddress, int localPort)

Creates a new streaming socket connected to the target host specified by the parameters dstName and dstPort.

Socket(String hostName, int port, boolean streaming)

This constructor was deprecated in API level 1. Use Socket(String, int) instead of this for streaming sockets or an appropriate constructor of DatagramSocket for UDP transport.

Socket(InetAddress dstAddress, int dstPort)

Creates a new streaming socket connected to the target host specified by the parameters dstAddress and dstPort.

Socket(InetAddress dstAddress, int dstPort, InetAddress localAddress, int localPort)

Creates a new streaming socket connected to the target host specified by the parameters dstAddress and dstPort.

Socket(InetAddress addr, int port, boolean streaming)

This constructor was deprecated in API level 1. Use Socket(InetAddress, int) instead of this for streaming sockets or an appropriate constructor of DatagramSocket for UDP transport.

Protected constructors

Socket(SocketImpl impl)

Creates an unconnected socket with the given socket implementation.

Public methods

void bind(SocketAddress localAddr)

Binds this socket to the given local host address and port specified by the SocketAddress localAddr.

void close()

Closes the socket.

void connect(SocketAddress remoteAddr, int timeout)

Connects this socket to the given remote host address and port specified by the SocketAddress remoteAddr with the specified timeout.

void connect(SocketAddress remoteAddr)

Connects this socket to the given remote host address and port specified by the SocketAddress remoteAddr.

SocketChannel getChannel()

Returns this socket's SocketChannel, if one exists.

InetAddress getInetAddress()

Returns the IP address of the target host this socket is connected to, or null if this socket is not yet connected.

InputStream getInputStream()

Returns an input stream to read data from this socket.

boolean getKeepAlive()

Returns this socket's SO_KEEPALIVE setting.

InetAddress getLocalAddress()

Returns the local IP address this socket is bound to, or an address for which isAnyLocalAddress() returns true if the socket is closed or unbound.

int getLocalPort()

Returns the local port this socket is bound to, or -1 if the socket is unbound.

SocketAddress getLocalSocketAddress()

Returns the local address and port of this socket as a SocketAddress or null if the socket has never been bound.

boolean getOOBInline()

Returns this socket's SO_OOBINLINE setting.

OutputStream getOutputStream()

Returns an output stream to write data into this socket.

int getPort()

Returns the port number of the target host this socket is connected to, or 0 if this socket is not yet connected.

int getReceiveBufferSize()

Returns this socket's receive buffer size.

SocketAddress getRemoteSocketAddress()

Returns the remote address and port of this socket as a SocketAddress or null if the socket is not connected.

boolean getReuseAddress()

Returns this socket's SO_REUSEADDR setting.

int getSendBufferSize()

Returns this socket's send buffer size.

int getSoLinger()

Returns this socket's linger timeout in seconds, or -1 for no linger (i.e.

int getSoTimeout()

Returns this socket's receive timeout.

boolean getTcpNoDelay()

Returns this socket's SocketOptions#TCP_NODELAY setting.

int getTrafficClass()

Returns this socket's setting.

boolean isBound()

Returns whether this socket is bound to a local address and port.

boolean isClosed()

Returns whether this socket is closed.

boolean isConnected()

Returns whether this socket is connected to a remote host.

boolean isInputShutdown()

Returns whether the incoming channel of the socket has already been closed.

boolean isOutputShutdown()

Returns whether the outgoing channel of the socket has already been closed.

void sendUrgentData(int value)

Sends the given single byte data which is represented by the lowest octet of value as "TCP urgent data".

void setKeepAlive(boolean keepAlive)

Sets this socket's SO_KEEPALIVE option.

void setOOBInline(boolean oobinline)

Sets this socket's SO_OOBINLINE option.

void setPerformancePreferences(int connectionTime, int latency, int bandwidth)

Sets performance preferences for connectionTime, latency and bandwidth.

void setReceiveBufferSize(int size)

Sets this socket's receive buffer size.

void setReuseAddress(boolean reuse)

Sets this socket's SO_REUSEADDR option.

void setSendBufferSize(int size)

Sets this socket's send buffer size.

void setSoLinger(boolean on, int timeout)

Sets this socket's linger timeout in seconds.

void setSoTimeout(int timeout)

Sets this socket's read timeout in milliseconds.

static void setSocketImplFactory(SocketImplFactory fac)

Sets the internal factory for creating socket implementations.

void setTcpNoDelay(boolean on)

Sets this socket's TCP_NODELAY option.

void setTrafficClass(int value)

Sets this socket's IP_TOS value for every packet sent by this socket.

void shutdownInput()

Closes the input stream of this socket.

void shutdownOutput()

Closes the output stream of this socket.

String toString()

Returns a String containing a concise, human-readable description of the socket.

Inherited methods

From class java.lang.Object
From interface java.io.Closeable
From interface java.lang.AutoCloseable

Public constructors

Socket

Added in API level 1
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:

Socket

Added in API level 1
Socket (Proxy proxy)

Creates a new unconnected socket using the given proxy type. When a SocketImplFactory is 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 SOCKS proxy server:
Socket sock = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("test.domain.org", 2130)));

Parameters
proxy Proxy: the specified proxy for this socket.
Throws
IllegalArgumentException if the argument proxy is null or of an invalid type.

See also:

Socket

Added in API level 1
Socket (String dstName, 
                int dstPort)

Creates a new streaming socket connected to the target host specified by the parameters dstName and dstPort. 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 String: the target host name or IP address to connect to.
dstPort int: 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

Added in API level 1
Socket (String dstName, 
                int dstPort, 
                InetAddress localAddress, 
                int localPort)

Creates a new streaming socket connected to the target host specified by the parameters dstName and dstPort. On the local endpoint the socket is bound to the given address localAddress on port localPort. If host is null a 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 String: the target host name or IP address to connect to.
dstPort int: the port on the target host to connect to.
localAddress InetAddress: the address on the local host to bind to.
localPort int: 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

Added in API level 1
Socket (String hostName, 
                int port, 
                boolean streaming)

This constructor was deprecated in API level 1.
Use Socket(String, int) instead of this for streaming sockets or an appropriate constructor of DatagramSocket for UDP transport.

Creates a new streaming or datagram socket connected to the target host specified by the parameters hostName and port. 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 String: the target host name or IP address to connect to.
port int: the port on the target host to connect to.
streaming boolean: if true a 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

Added in API level 1
Socket (InetAddress dstAddress, 
                int dstPort)

Creates a new streaming socket connected to the target host specified by the parameters dstAddress and dstPort. The socket is bound to any available port on the local host using a wildcard address.

Parameters
dstAddress InetAddress: the target host address to connect to.
dstPort int: the port on the target host to connect to.
Throws
IOException if an error occurs while creating the socket.

Socket

Added in API level 1
Socket (InetAddress dstAddress, 
                int dstPort, 
                InetAddress localAddress, 
                int localPort)

Creates a new streaming socket connected to the target host specified by the parameters dstAddress and dstPort.

On the local endpoint the socket is bound to the given address localAddress on port localPort. If localAddress is null the socket will be bound to a wildcard address.

Parameters
dstAddress InetAddress: the target host address to connect to.
dstPort int: the port on the target host to connect to.
localAddress InetAddress: the address on the local host to bind to, or null.
localPort int: the port on the local host to bind to.
Throws
IOException if an error occurs while creating the socket.

Socket

Added in API level 1
Socket (InetAddress addr, 
                int port, 
                boolean streaming)

This constructor was deprecated in API level 1.
Use Socket(InetAddress, int) instead of this for streaming sockets or an appropriate constructor of DatagramSocket for UDP transport.

Creates a new streaming or datagram socket connected to the target host specified by the parameters addr and port. The socket is bound to any available port on the local host using a wildcard address.

Parameters
addr InetAddress: the Internet address to connect to.
port int: the port on the target host to connect to.
streaming boolean: if true a streaming socket is returned, a datagram socket otherwise.
Throws
IOException if an error occurs while creating the socket.

Protected constructors

Socket

Added in API level 1
Socket (SocketImpl impl)

Creates an unconnected socket with the given socket implementation.

Parameters
impl SocketImpl: the socket implementation to be used.
Throws
SocketException if an error occurs while creating the socket.

Public methods

bind

Added in API level 1
void bind (SocketAddress localAddr)

Binds this socket to the given local host address and port specified by the SocketAddress localAddr. If localAddr is set to null, this socket will be bound to an available local address on any free port.

Parameters
localAddr SocketAddress: 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.

close

Added in API level 1
void close ()

Closes the socket. It is not possible to reconnect or rebind to this socket thereafter which means a new socket instance has to be created.

Throws
IOException if an error occurs while closing the socket.

connect

Added in API level 1
void connect (SocketAddress remoteAddr, 
                int timeout)

Connects this socket to the given remote host address and port specified by the SocketAddress remoteAddr with the specified timeout. The connecting method will block until the connection is established or an error occurred.

Parameters
remoteAddr SocketAddress: the address and port of the remote host to connect to.
timeout int: the timeout value in milliseconds or 0 for 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.

connect

Added in API level 1
void connect (SocketAddress remoteAddr)

Connects this socket to the given remote host address and port specified by the SocketAddress remoteAddr.

Parameters
remoteAddr SocketAddress: 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.

getChannel

Added in API level 1
SocketChannel getChannel ()

Returns this socket's SocketChannel, 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 by accept() or open().

Returns
SocketChannel

getInetAddress

Added in API level 1
InetAddress getInetAddress ()

Returns the IP address of the target host this socket is connected to, or null if this socket is not yet connected.

Returns
InetAddress

getInputStream

Added in API level 1
InputStream getInputStream ()

Returns an input stream to read data from this socket. If the socket has an associated SocketChannel and that channel is in non-blocking mode then reads from the stream will throw a IllegalBlockingModeException.

Returns
InputStream 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

Added in API level 1
boolean getKeepAlive ()

Returns this socket's SO_KEEPALIVE setting.

Returns
boolean
Throws
SocketException

getLocalAddress

Added in API level 1
InetAddress getLocalAddress ()

Returns the local IP address this socket is bound to, or an address for which isAnyLocalAddress() returns true if the socket is closed or unbound.

Returns
InetAddress

getLocalPort

Added in API level 1
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.

Returns
int

getLocalSocketAddress

Added in API level 1
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 which isAnyLocalAddress() returns true will be returned with the previously-bound port. This is useful on multihomed hosts.

Returns
SocketAddress

getOOBInline

Added in API level 1
boolean getOOBInline ()

Returns this socket's SO_OOBINLINE setting.

Returns
boolean
Throws
SocketException

getOutputStream

Added in API level 1
OutputStream getOutputStream ()

Returns an output stream to write data into this socket. If the socket has an associated SocketChannel and that channel is in non-blocking mode then writes to the stream will throw a IllegalBlockingModeException.

Returns
OutputStream 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

Added in API level 1
int getPort ()

Returns the port number of the target host this socket is connected to, or 0 if this socket is not yet connected.

Returns
int

getReceiveBufferSize

Added in API level 1
int getReceiveBufferSize ()

Returns this socket's receive buffer size.

Returns
int
Throws
SocketException

getRemoteSocketAddress

Added in API level 1
SocketAddress getRemoteSocketAddress ()

Returns the remote address and port of this socket as a SocketAddress or null if the socket is not connected.

Returns
SocketAddress the remote socket address and port.

getReuseAddress

Added in API level 1
boolean getReuseAddress ()

Returns this socket's SO_REUSEADDR setting.

Returns
boolean
Throws
SocketException

getSendBufferSize

Added in API level 1
int getSendBufferSize ()

Returns this socket's send buffer size.

Returns
int
Throws
SocketException

getSoLinger

Added in API level 1
int getSoLinger ()

Returns this socket's linger timeout in seconds, or -1 for no linger (i.e. close will return immediately).

Returns
int
Throws
SocketException

getSoTimeout

Added in API level 1
int getSoTimeout ()

Returns this socket's receive timeout.

Returns
int
Throws
SocketException

getTcpNoDelay

Added in API level 1
boolean getTcpNoDelay ()

Returns this socket's SocketOptions#TCP_NODELAY setting.

Returns
boolean
Throws
SocketException

getTrafficClass

Added in API level 1
int getTrafficClass ()

Returns this socket's setting.

Returns
int
Throws
SocketException

See also:

isBound

Added in API level 1
boolean isBound ()

Returns whether this socket is bound to a local address and port.

Returns
boolean true if the socket is bound to a local address, false otherwise.

isClosed

Added in API level 1
boolean isClosed ()

Returns whether this socket is closed.

Returns
boolean true if the socket is closed, false otherwise.

isConnected

Added in API level 1
boolean isConnected ()

Returns whether this socket is connected to a remote host.

Returns
boolean true if the socket is connected, false otherwise.

isInputShutdown

Added in API level 1
boolean isInputShutdown ()

Returns whether the incoming channel of the socket has already been closed.

Returns
boolean true if reading from this socket is not possible anymore, false otherwise.

isOutputShutdown

Added in API level 1
boolean isOutputShutdown ()

Returns whether the outgoing channel of the socket has already been closed.

Returns
boolean true if writing to this socket is not possible anymore, false otherwise.

sendUrgentData

Added in API level 1
void sendUrgentData (int value)

Sends the given single byte data which is represented by the lowest octet of value as "TCP urgent data".

Parameters
value int: the byte of urgent data to be sent.
Throws
IOException if an error occurs while sending urgent data.

setKeepAlive

Added in API level 1
void setKeepAlive (boolean keepAlive)

Sets this socket's SO_KEEPALIVE option.

Parameters
keepAlive boolean
Throws
SocketException

setOOBInline

Added in API level 1
void setOOBInline (boolean oobinline)

Sets this socket's SO_OOBINLINE option.

Parameters
oobinline boolean
Throws
SocketException

setPerformancePreferences

Added in API level 1
void setPerformancePreferences (int connectionTime, 
                int latency, 
                int bandwidth)

Sets performance preferences for connectionTime, latency and bandwidth.

This method does currently nothing.

Parameters
connectionTime int: the value representing the importance of a short connecting time.
latency int: the value representing the importance of low latency.
bandwidth int: the value representing the importance of high bandwidth.

setReceiveBufferSize

Added in API level 1
void setReceiveBufferSize (int size)

Sets this socket's receive buffer size.

Parameters
size int
Throws
SocketException

setReuseAddress

Added in API level 1
void setReuseAddress (boolean reuse)

Sets this socket's SO_REUSEADDR option.

Parameters
reuse boolean
Throws
SocketException

setSendBufferSize

Added in API level 1
void setSendBufferSize (int size)

Sets this socket's send buffer size.

Parameters
size int
Throws
SocketException

setSoLinger

Added in API level 1
void setSoLinger (boolean on, 
                int timeout)

Sets this socket's linger timeout in seconds. If on is false, timeout is irrelevant.

Parameters
on boolean
timeout int
Throws
SocketException

setSoTimeout

Added in API level 1
void setSoTimeout (int timeout)

Sets this socket's read timeout in milliseconds. Use 0 for no timeout. To take effect, this option must be set before the blocking method was called.

Parameters
timeout int
Throws
SocketException

setSocketImplFactory

Added in API level 1
void setSocketImplFactory (SocketImplFactory fac)

Sets the internal factory for creating socket implementations. This may only be executed once during the lifetime of the application.

Parameters
fac SocketImplFactory: the socket implementation factory to be set.
Throws
IOException if the factory has been already set.

setTcpNoDelay

Added in API level 1
void setTcpNoDelay (boolean on)

Sets this socket's TCP_NODELAY option.

Parameters
on boolean
Throws
SocketException

setTrafficClass

Added in API level 1
void setTrafficClass (int value)

Sets this socket's IP_TOS value for every packet sent by this socket.

Parameters
value int
Throws
SocketException

shutdownInput

Added in API level 1
void shutdownInput ()

Closes 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 value EOF.

Throws
IOException if an error occurs while closing the socket input stream.
SocketException if the input stream is already closed.

shutdownOutput

Added in API level 1
void shutdownOutput ()

Closes 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 an IOException.

Throws
IOException if an error occurs while closing the socket output stream.
SocketException if the output stream is already closed.

toString

Added in API level 1
String toString ()

Returns a String containing a concise, human-readable description of the socket.

Returns
String the textual representation of this socket.
This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.