- All Implemented Interfaces:
Closeable,AutoCloseable,ByteChannel,Channel,GatheringByteChannel,InterruptibleChannel,NetworkChannel,ReadableByteChannel,ScatteringByteChannel,WritableByteChannel
public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
A socket channel is created by invoking one of the open
methods of this class. It is not possible to create a channel for an arbitrary,
pre-existing socket. A newly-created socket channel is open but not yet
connected. An attempt to invoke an I/O operation upon an unconnected
channel will cause a NotYetConnectedException to be thrown. A
socket channel can be connected by invoking its connect
method; once connected, a socket channel remains connected until it is
closed. Whether or not a socket channel is connected may be determined by
invoking its isConnected method.
Socket channels support non-blocking connection: A socket
channel may be created and the process of establishing the link to the
remote socket may be initiated via the connect method for
later completion by the finishConnect method.
Whether or not a connection operation is in progress may be determined by
invoking the isConnectionPending method.
Socket channels support asynchronous shutdown, which is similar
to the asynchronous close operation specified in the Channel class.
If the input side of a socket is shut down by one thread while another
thread is blocked in a read operation on the socket's channel, then the read
operation in the blocked thread will complete without reading any bytes and
will return -1. If the output side of a socket is shut down by one
thread while another thread is blocked in a write operation on the socket's
channel, then the blocked thread will receive an AsynchronousCloseException.
Socket options are configured using the setOption method. Socket channels support the following options:
Additional (implementation specific) options may also be supported.
Option Name Description SO_SNDBUFThe size of the socket send buffer SO_RCVBUFThe size of the socket receive buffer SO_KEEPALIVEKeep connection alive SO_REUSEADDRRe-use address SO_LINGERLinger on close if data is present (when configured in blocking mode only) TCP_NODELAYDisable the Nagle algorithm
Socket channels are safe for use by multiple concurrent threads. They
support concurrent reading and writing, though at most one thread may be
reading and at most one thread may be writing at any given time. The connect and finishConnect methods are
mutually synchronized against each other, and an attempt to initiate a read
or write operation while an invocation of one of these methods is in
progress will block until that invocation is complete.
- Since:
- 1.4
-
Constructor Summary
Constructors Modifier Constructor Description protectedSocketChannel(SelectorProvider provider)Initializes a new instance of this class. -
Method Summary
Modifier and Type Method Description abstract SocketChannelbind(SocketAddress local)Binds the channel's socket to a local address.abstract booleanconnect(SocketAddress remote)Connects this channel's socket.abstract booleanfinishConnect()Finishes the process of connecting a socket channel.abstract SocketAddressgetLocalAddress()Returns the socket address that this channel's socket is bound to.abstract SocketAddressgetRemoteAddress()Returns the remote address to which this channel's socket is connected.abstract booleanisConnected()Tells whether or not this channel's network socket is connected.abstract booleanisConnectionPending()Tells whether or not a connection operation is in progress on this channel.static SocketChannelopen()Opens a socket channel.static SocketChannelopen(SocketAddress remote)Opens a socket channel and connects it to a remote address.abstract intread(ByteBuffer dst)Reads a sequence of bytes from this channel into the given buffer.longread(ByteBuffer[] dsts)Reads a sequence of bytes from this channel into the given buffers.abstract longread(ByteBuffer[] dsts, int offset, int length)Reads a sequence of bytes from this channel into a subsequence of the given buffers.abstract <T> SocketChannelsetOption(SocketOption<T> name, T value)Sets the value of a socket option.abstract SocketChannelshutdownInput()Shutdown the connection for reading without closing the channel.abstract SocketChannelshutdownOutput()Shutdown the connection for writing without closing the channel.abstract Socketsocket()Retrieves a socket associated with this channel.intvalidOps()Returns an operation set identifying this channel's supported operations.abstract intwrite(ByteBuffer src)Writes a sequence of bytes to this channel from the given buffer.longwrite(ByteBuffer[] srcs)Writes a sequence of bytes to this channel from the given buffers.abstract longwrite(ByteBuffer[] srcs, int offset, int length)Writes a sequence of bytes to this channel from a subsequence of the given buffers.Methods declared in class java.nio.channels.spi.AbstractSelectableChannel
configureBlocking, implCloseChannel, implCloseSelectableChannel, implConfigureBlocking, provider, registerMethods declared in class java.nio.channels.SelectableChannel
blockingLock, isBlocking, isRegistered, keyFor, register
-
Constructor Details
-
SocketChannel
Initializes a new instance of this class.- Parameters:
provider- The provider that created this channel
-
-
Method Details
-
open
Opens a socket channel.The new channel is created by invoking the
openSocketChannelmethod of the system-wide defaultSelectorProviderobject.- Returns:
- A new socket channel
- Throws:
IOException- If an I/O error occurs
-
open
Opens a socket channel and connects it to a remote address.This convenience method works as if by invoking the
open()method, invoking theconnectmethod upon the resulting socket channel, passing itremote, and then returning that channel.- Parameters:
remote- The remote address to which the new channel is to be connected- Returns:
- A new, and connected, socket channel
- Throws:
AsynchronousCloseException- If another thread closes this channel while the connect operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the connect operation is in progress, thereby closing the channel and setting the current thread's interrupt statusUnresolvedAddressException- If the given remote address is not fully resolvedUnsupportedAddressTypeException- If the type of the given remote address is not supportedSecurityException- If a security manager has been installed and it does not permit access to the given remote endpointIOException- If some other I/O error occurs
-
validOps
public final int validOps()Returns an operation set identifying this channel's supported operations.Socket channels support connecting, reading, and writing, so this method returns
(SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE).- Specified by:
validOpsin classSelectableChannel- Returns:
- The valid-operation set
-
bind
Description copied from interface:NetworkChannelBinds the channel's socket to a local address.This method is used to establish an association between the socket and a local address. Once an association is established then the socket remains bound until the channel is closed. If the
localparameter has the valuenullthen the socket will be bound to an address that is assigned automatically.- Specified by:
bindin interfaceNetworkChannel- Parameters:
local- The address to bind the socket, ornullto bind the socket to an automatically assigned socket address- Returns:
- This channel
- Throws:
ConnectionPendingException- If a non-blocking connect operation is already in progress on this channelAlreadyBoundException- If the socket is already boundUnsupportedAddressTypeException- If the type of the given address is not supportedClosedChannelException- If the channel is closedIOException- If some other I/O error occursSecurityException- If a security manager has been installed and itscheckListenmethod denies the operation- Since:
- 1.7
- See Also:
NetworkChannel.getLocalAddress()
-
setOption
Description copied from interface:NetworkChannelSets the value of a socket option.- Specified by:
setOptionin interfaceNetworkChannel- Type Parameters:
T- The type of the socket option value- Parameters:
name- The socket optionvalue- The value of the socket option. A value ofnullmay be a valid value for some socket options.- Returns:
- This channel
- Throws:
UnsupportedOperationException- If the socket option is not supported by this channelIllegalArgumentException- If the value is not a valid value for this socket optionClosedChannelException- If this channel is closedIOException- If an I/O error occurs- Since:
- 1.7
- See Also:
StandardSocketOptions
-
shutdownInput
Shutdown the connection for reading without closing the channel.Once shutdown for reading then further reads on the channel will return
-1, the end-of-stream indication. If the input side of the connection is already shutdown then invoking this method has no effect.- Returns:
- The channel
- Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedIOException- If some other I/O error occurs- Since:
- 1.7
-
shutdownOutput
Shutdown the connection for writing without closing the channel.Once shutdown for writing then further attempts to write to the channel will throw
ClosedChannelException. If the output side of the connection is already shutdown then invoking this method has no effect.- Returns:
- The channel
- Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedIOException- If some other I/O error occurs- Since:
- 1.7
-
socket
Retrieves a socket associated with this channel.The returned object will not declare any public methods that are not declared in the
Socketclass.- Returns:
- A socket associated with this channel
-
isConnected
public abstract boolean isConnected()Tells whether or not this channel's network socket is connected.- Returns:
trueif, and only if, this channel's network socket isopenand connected
-
isConnectionPending
public abstract boolean isConnectionPending()Tells whether or not a connection operation is in progress on this channel.- Returns:
trueif, and only if, a connection operation has been initiated on this channel but not yet completed by invoking thefinishConnectmethod
-
connect
Connects this channel's socket.If this channel is in non-blocking mode then an invocation of this method initiates a non-blocking connection operation. If the connection is established immediately, as can happen with a local connection, then this method returns
true. Otherwise this method returnsfalseand the connection operation must later be completed by invoking thefinishConnectmethod.If this channel is in blocking mode then an invocation of this method will block until the connection is established or an I/O error occurs.
This method performs exactly the same security checks as the
Socketclass. That is, if a security manager has been installed then this method verifies that itscheckConnectmethod permits connecting to the address and port number of the given remote endpoint.This method may be invoked at any time. If a read or write operation upon this channel is invoked while an invocation of this method is in progress then that operation will first block until this invocation is complete. If a connection attempt is initiated but fails, that is, if an invocation of this method throws a checked exception, then the channel will be closed.
- Parameters:
remote- The remote address to which this channel is to be connected- Returns:
trueif a connection was established,falseif this channel is in non-blocking mode and the connection operation is in progress- Throws:
AlreadyConnectedException- If this channel is already connectedConnectionPendingException- If a non-blocking connection operation is already in progress on this channelClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the connect operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the connect operation is in progress, thereby closing the channel and setting the current thread's interrupt statusUnresolvedAddressException- If the given remote address is not fully resolvedUnsupportedAddressTypeException- If the type of the given remote address is not supportedSecurityException- If a security manager has been installed and it does not permit access to the given remote endpointIOException- If some other I/O error occurs
-
finishConnect
Finishes the process of connecting a socket channel.A non-blocking connection operation is initiated by placing a socket channel in non-blocking mode and then invoking its
connectmethod. Once the connection is established, or the attempt has failed, the socket channel will become connectable and this method may be invoked to complete the connection sequence. If the connection operation failed then invoking this method will cause an appropriateIOExceptionto be thrown.If this channel is already connected then this method will not block and will immediately return
true. If this channel is in non-blocking mode then this method will returnfalseif the connection process is not yet complete. If this channel is in blocking mode then this method will block until the connection either completes or fails, and will always either returntrueor throw a checked exception describing the failure.This method may be invoked at any time. If a read or write operation upon this channel is invoked while an invocation of this method is in progress then that operation will first block until this invocation is complete. If a connection attempt fails, that is, if an invocation of this method throws a checked exception, then the channel will be closed.
- Returns:
trueif, and only if, this channel's socket is now connected- Throws:
NoConnectionPendingException- If this channel is not connected and a connection operation has not been initiatedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the connect operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the connect operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
getRemoteAddress
Returns the remote address to which this channel's socket is connected.Where the channel is bound and connected to an Internet Protocol socket address then the return value from this method is of type
InetSocketAddress.- Returns:
- The remote address;
nullif the channel's socket is not connected - Throws:
ClosedChannelException- If the channel is closedIOException- If an I/O error occurs- Since:
- 1.7
-
read
Description copied from interface:ReadableByteChannelReads a sequence of bytes from this channel into the given buffer.An attempt is made to read up to r bytes from the channel, where r is the number of bytes remaining in the buffer, that is,
dst.remaining(), at the moment this method is invoked.Suppose that a byte sequence of length n is read, where
0<=n<=r. This byte sequence will be transferred into the buffer so that the first byte in the sequence is at index p and the last byte is at index p+n-1, where p is the buffer's position at the moment this method is invoked. Upon return the buffer's position will be equal to p+n; its limit will not have changed.A read operation might not fill the buffer, and in fact it might not read any bytes at all. Whether or not it does so depends upon the nature and state of the channel. A socket channel in non-blocking mode, for example, cannot read any more bytes than are immediately available from the socket's input buffer; similarly, a file channel cannot read any more bytes than remain in the file. It is guaranteed, however, that if a channel is in blocking mode and there is at least one byte remaining in the buffer then this method will block until at least one byte is read.
This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete.
- Specified by:
readin interfaceReadableByteChannel- Parameters:
dst- The buffer into which bytes are to be transferred- Returns:
- The number of bytes read, possibly zero, or
-1if the channel has reached end-of-stream - Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
read
Description copied from interface:ScatteringByteChannelReads a sequence of bytes from this channel into a subsequence of the given buffers.An invocation of this method attempts to read up to r bytes from this channel, where r is the total number of bytes remaining the specified subsequence of the given buffer array, that is,
at the moment that this method is invoked.dsts[offset].remaining() + dsts[offset+1].remaining() + ... + dsts[offset+length-1].remaining()Suppose that a byte sequence of length n is read, where
0<=n<=r. Up to the firstdsts[offset].remaining()bytes of this sequence are transferred into bufferdsts[offset], up to the nextdsts[offset+1].remaining()bytes are transferred into bufferdsts[offset+1], and so forth, until the entire byte sequence is transferred into the given buffers. As many bytes as possible are transferred into each buffer, hence the final position of each updated buffer, except the last updated buffer, is guaranteed to be equal to that buffer's limit.This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete.
- Specified by:
readin interfaceScatteringByteChannel- Parameters:
dsts- The buffers into which bytes are to be transferredoffset- The offset within the buffer array of the first buffer into which bytes are to be transferred; must be non-negative and no larger thandsts.lengthlength- The maximum number of buffers to be accessed; must be non-negative and no larger thandsts.length-offset- Returns:
- The number of bytes read, possibly zero,
or
-1if the channel has reached end-of-stream - Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
read
Description copied from interface:ScatteringByteChannelReads a sequence of bytes from this channel into the given buffers.An invocation of this method of the form
c.read(dsts)behaves in exactly the same manner as the invocationc.read(dsts, 0, dsts.length);
- Specified by:
readin interfaceScatteringByteChannel- Parameters:
dsts- The buffers into which bytes are to be transferred- Returns:
- The number of bytes read, possibly zero,
or
-1if the channel has reached end-of-stream - Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
write
Description copied from interface:WritableByteChannelWrites a sequence of bytes to this channel from the given buffer.An attempt is made to write up to r bytes to the channel, where r is the number of bytes remaining in the buffer, that is,
src.remaining(), at the moment this method is invoked.Suppose that a byte sequence of length n is written, where
0<=n<=r. This byte sequence will be transferred from the buffer starting at index p, where p is the buffer's position at the moment this method is invoked; the index of the last byte written will be p+n-1. Upon return the buffer's position will be equal to p+n; its limit will not have changed.Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.
This method may be invoked at any time. If another thread has already initiated a write operation upon this channel, however, then an invocation of this method will block until the first operation is complete.
- Specified by:
writein interfaceWritableByteChannel- Parameters:
src- The buffer from which bytes are to be retrieved- Returns:
- The number of bytes written, possibly zero
- Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the write operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
write
Description copied from interface:GatheringByteChannelWrites a sequence of bytes to this channel from a subsequence of the given buffers.An attempt is made to write up to r bytes to this channel, where r is the total number of bytes remaining in the specified subsequence of the given buffer array, that is,
at the moment that this method is invoked.srcs[offset].remaining() + srcs[offset+1].remaining() + ... + srcs[offset+length-1].remaining()Suppose that a byte sequence of length n is written, where
0<=n<=r. Up to the firstsrcs[offset].remaining()bytes of this sequence are written from buffersrcs[offset], up to the nextsrcs[offset+1].remaining()bytes are written from buffersrcs[offset+1], and so forth, until the entire byte sequence is written. As many bytes as possible are written from each buffer, hence the final position of each updated buffer, except the last updated buffer, is guaranteed to be equal to that buffer's limit.Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.
This method may be invoked at any time. If another thread has already initiated a write operation upon this channel, however, then an invocation of this method will block until the first operation is complete.
- Specified by:
writein interfaceGatheringByteChannel- Parameters:
srcs- The buffers from which bytes are to be retrievedoffset- The offset within the buffer array of the first buffer from which bytes are to be retrieved; must be non-negative and no larger thansrcs.lengthlength- The maximum number of buffers to be accessed; must be non-negative and no larger thansrcs.length-offset- Returns:
- The number of bytes written, possibly zero
- Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the write operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
write
Description copied from interface:GatheringByteChannelWrites a sequence of bytes to this channel from the given buffers.An invocation of this method of the form
c.write(srcs)behaves in exactly the same manner as the invocationc.write(srcs, 0, srcs.length);
- Specified by:
writein interfaceGatheringByteChannel- Parameters:
srcs- The buffers from which bytes are to be retrieved- Returns:
- The number of bytes written, possibly zero
- Throws:
NotYetConnectedException- If this channel is not yet connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the write operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
getLocalAddress
Returns the socket address that this channel's socket is bound to.Where the channel is
boundto an Internet Protocol socket address then the return value from this method is of typeInetSocketAddress.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. If the operation is not allowed, aSocketAddressrepresenting theloopbackaddress and the local port of the channel's socket is returned.- Specified by:
getLocalAddressin interfaceNetworkChannel- Returns:
- The
SocketAddressthat the socket is bound to, or theSocketAddressrepresenting the loopback address if denied by the security manager, ornullif the channel's socket is not bound - Throws:
ClosedChannelException- If the channel is closedIOException- If an I/O error occurs
-