Class SocketChannel
- All Implemented Interfaces:
Closeable,AutoCloseable,ByteChannel,Channel,GatheringByteChannel,InterruptibleChannel,ReadableByteChannel,ScatteringByteChannel,WritableByteChannel
public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel
SocketChannel is a selectable channel that provides a partial
abstraction of stream connecting socket. socket() returns the related
Socket instance which can handle the socket.
A socket channel is open but not connected when created by open().
After connecting it by calling connect(SocketAddress), it will remain
connected until it gets closed. If the connection is non-blocking then
connect(SocketAddress) is used to initiate the connection, followed
by a call of finishConnect() to perform the final steps of
connecting. isConnectionPending() indicates if the connection is
blocked or not; isConnected() indicates if the socket is finally
connected or not.
The input and output sides of a channel can be shut down independently and
asynchronously without closing the channel. The shutdownInput method
is used for the input side of a channel and subsequent read operations return
-1, which means end of stream. If another thread is blocked in a read
operation when the shutdown occurs, the read will end without effect and
return end of stream. The shutdownOutput method is used for the
output side of the channel; subsequent write operations throw a
ClosedChannelException. If the output is shut down and another thread
is blocked in a write operation, an AsynchronousCloseException will
be thrown to the pending thread.
Socket channels are thread-safe, no more than one thread can read or write at
any given time. The connect(SocketAddress) and
finishConnect() methods are synchronized against each other; when they are
processing, calls to read and write will block.
-
Constructor Summary
Constructors Modifier Constructor Description protectedSocketChannel(SelectorProvider selectorProvider)Constructs a newSocketChannel. -
Method Summary
Modifier and Type Method Description abstract booleanconnect(SocketAddress address)Connects this channel's socket with a remote address.abstract booleanfinishConnect()Completes the connection process initiated by a call ofconnect(SocketAddress).abstract booleanisConnected()Indicates whether this channel's socket is connected.abstract booleanisConnectionPending()Indicates whether this channel's socket is still trying to connect.static SocketChannelopen()Creates an open and unconnected socket channel.static SocketChannelopen(SocketAddress address)Creates a socket channel and connects it to a socket address.abstract intread(ByteBuffer target)Reads bytes from this socket channel into the given buffer.longread(ByteBuffer[] targets)Reads bytes from this socket channel and stores them in the specified array of buffers.abstract longread(ByteBuffer[] targets, int offset, int length)Reads bytes from this socket channel into a subset of the given buffers.abstract Socketsocket()Returns the socket assigned to this channel, which does not declare any public methods that are not declared inSocket.intvalidOps()Gets the valid operations of this channel.abstract intwrite(ByteBuffer source)Writes bytes from the given byte buffer to this socket channel.longwrite(ByteBuffer[] sources)Writes bytes from all the given byte buffers to this socket channel.abstract longwrite(ByteBuffer[] sources, int offset, int length)Attempts to write a subset of the given bytes from the buffers to this socket channel.Methods inherited from class java.nio.channels.spi.AbstractSelectableChannel
blockingLock, configureBlocking, implCloseChannel, implCloseSelectableChannel, implConfigureBlocking, isBlocking, isRegistered, keyFor, provider, registerMethods inherited from class java.nio.channels.SelectableChannel
registerMethods inherited from class java.nio.channels.spi.AbstractInterruptibleChannel
begin, close, end, isOpen
-
Constructor Details
-
SocketChannel
Constructs a newSocketChannel.- Parameters:
selectorProvider- an instance of SelectorProvider.
-
-
Method Details
-
open
Creates an open and unconnected socket channel.This channel is created by calling
openSocketChannel()of the defaultSelectorProviderinstance.- Returns:
- the new channel which is open but unconnected.
- Throws:
IOException- if an I/O error occurs.
-
open
Creates a socket channel and connects it to a socket address.This method performs a call to
open()followed by a call toconnect(SocketAddress).- Parameters:
address- the socket address to be connected to.- Returns:
- the new connected channel.
- Throws:
AsynchronousCloseException- if this channel is closed by another thread while this method is executing.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is executing. The calling thread will have the interrupt state set and the channel will be closed.UnresolvedAddressException- if the address is not resolved.UnsupportedAddressTypeException- if the address type is not supported.IOException- if an I/O error occurs.
-
validOps
public final int validOps()Gets the valid operations of this channel. Socket channels support connect, read and write operation, so this method returnsSelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE.- Specified by:
validOpsin classSelectableChannel- Returns:
- the operations supported by this channel.
- See Also:
SelectableChannel.validOps()
-
socket
Returns the socket assigned to this channel, which does not declare any public methods that are not declared inSocket.- Returns:
- the socket assigned to this channel.
-
isConnected
public abstract boolean isConnected()Indicates whether this channel's socket is connected.- Returns:
trueif this channel's socket is connected,falseotherwise.
-
isConnectionPending
public abstract boolean isConnectionPending()Indicates whether this channel's socket is still trying to connect.- Returns:
trueif the connection is initiated but not finished;falseotherwise.
-
connect
Connects this channel's socket with a remote address.If this channel is blocking, this method will suspend until connecting is finished or an I/O exception occurs. If the channel is non-blocking, this method will return
trueif the connection is finished at once or returnfalsewhen the connection must be finished later by callingfinishConnect().This method can be called at any moment and can block other read and write operations while connecting. It executes the same security checks as the connect method of the
Socketclass.- Parameters:
address- the address to connect with.- Returns:
trueif the connection is finished,falseotherwise.- Throws:
AlreadyConnectedException- if the channel is already connected.ConnectionPendingException- a non-blocking connecting operation is already executing on this channel.ClosedChannelException- if this channel is closed.AsynchronousCloseException- if this channel is closed by another thread while this method is executing.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The calling thread will have the interrupt state set and this channel will be closed.UnresolvedAddressException- if the address is not resolved.UnsupportedAddressTypeException- if the address type is not supported.IOException- if an I/O error occurs.
-
finishConnect
Completes the connection process initiated by a call ofconnect(SocketAddress).This method returns
trueif the connection is finished already and returnsfalseif the channel is non-blocking and the connection is not finished yet.If this channel is in blocking mode, this method will suspend and return
truewhen the connection is finished. It closes this channel and throws an exception if the connection fails.This method can be called at any moment and it can block other
readandwriteoperations while connecting.- Returns:
trueif the connection is successfully finished,falseotherwise.- Throws:
NoConnectionPendingException- if the channel is not connected and the connection process has not been initiated.ClosedChannelException- if this channel is closed.AsynchronousCloseException- if this channel is closed by another thread while this method is executing.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The calling thread has the interrupt state set, and this channel is closed.IOException- if an I/O error occurs.
-
read
Reads bytes from this socket channel into the given buffer.The maximum number of bytes that will be read is the remaining number of bytes in the buffer when the method is invoked. The bytes will be copied into the buffer starting at the buffer's current position.
The call may block if other threads are also attempting to read from this channel.
Upon completion, the buffer's position is set to the end of the bytes that have been read. The buffer's limit is not changed.
- Specified by:
readin interfaceReadableByteChannel- Parameters:
target- the byte buffer to receive the bytes.- Returns:
- the number of bytes actually read.
- Throws:
AsynchronousCloseException- if another thread closes the channel during the read.NotYetConnectedException- if this channel is not yet connected.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The interrupt state of the calling thread is set and the channel is closed.ClosedChannelException- if this channel is closed.IOException- if another I/O error occurs.- See Also:
ReadableByteChannel.read(java.nio.ByteBuffer)
-
read
Reads bytes from this socket channel into a subset of the given buffers. This method attempts to read allremaining()bytes fromlengthbyte buffers, in order, starting attargets[offset]. The number of bytes actually read is returned.If a read operation is in progress, subsequent threads will block until the read is completed and will then contend for the ability to read.
- Specified by:
readin interfaceScatteringByteChannel- Parameters:
targets- the array of byte buffers into which the bytes will be copied.offset- the index of the first buffer to store bytes in.length- the maximum number of buffers to store bytes in.- Returns:
- the number of bytes actually read.
- Throws:
AsynchronousCloseException- if this channel is closed by another thread during this read operation.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The interrupt state of the calling thread is set and the channel is closed.ClosedChannelException- if this channel is closed.IndexOutOfBoundsException- ifoffset < 0orlength < 0, or ifoffset + lengthis greater than the size oftargets.IOException- if another I/O error occurs.NotYetConnectedException- if this channel is not yet connected.- See Also:
ScatteringByteChannel.read(java.nio.ByteBuffer[], int, int)
-
read
Reads bytes from this socket channel and stores them in the specified array of buffers. This method attempts to read as many bytes as can be stored in the buffer array from this channel and returns the number of bytes actually read.If a read operation is in progress, subsequent threads will block until the read is completed and will then contend for the ability to read.
Calling this method is equivalent to calling
read(targets, 0, targets.length);- Specified by:
readin interfaceScatteringByteChannel- Parameters:
targets- the array of byte buffers into which the bytes will be copied.- Returns:
- the number of bytes actually read.
- Throws:
AsynchronousCloseException- if this channel is closed by another thread during this read operation.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The interrupt state of the calling thread is set and the channel is closed.ClosedChannelException- if this channel is closed.IOException- if another I/O error occurs.NotYetConnectedException- if this channel is not yet connected.
-
write
Writes bytes from the given byte buffer to this socket channel. The maximum number of bytes that are written is the remaining number of bytes in the buffer when this method is invoked. The bytes are taken from the buffer starting at the buffer's position.The call may block if other threads are also attempting to write to the same channel.
Upon completion, the buffer's position is updated to the end of the bytes that have been written. The buffer's limit is not changed.
- Specified by:
writein interfaceWritableByteChannel- Parameters:
source- the byte buffer containing the bytes to be written.- Returns:
- the number of bytes actually written.
- Throws:
AsynchronousCloseException- if another thread closes the channel during the write.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The interrupt state of the calling thread is set and the channel is closed.ClosedChannelException- if the channel was already closed.IOException- if another I/O error occurs.NotYetConnectedException- if this channel is not connected yet.- See Also:
WritableByteChannel.write(java.nio.ByteBuffer)
-
write
Attempts to write a subset of the given bytes from the buffers to this socket channel. This method attempts to write allremaining()bytes fromlengthbyte buffers, in order, starting atsources[offset]. The number of bytes actually written is returned.If a write operation is in progress, subsequent threads will block until the write is completed and then contend for the ability to write.
- Specified by:
writein interfaceGatheringByteChannel- Parameters:
sources- the array of byte buffers that is the source for bytes written to this channel.offset- the index of the first buffer inbuffersto get bytes from.length- the number of buffers to get bytes from.- Returns:
- the number of bytes actually written to this channel.
- Throws:
AsynchronousCloseException- if this channel is closed by another thread during this write operation.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The interrupt state of the calling thread is set and the channel is closed.ClosedChannelException- if this channel is closed.IndexOutOfBoundsException- ifoffset < 0orlength < 0, or ifoffset + lengthis greater than the size ofsources.IOException- if another I/O error occurs.NotYetConnectedException- if this channel is not yet connected.- See Also:
GatheringByteChannel.write(java.nio.ByteBuffer[], int, int)
-
write
Writes bytes from all the given byte buffers to this socket channel.Calling this method is equivalent to calling
write(sources, 0, sources.length);- Specified by:
writein interfaceGatheringByteChannel- Parameters:
sources- the buffers containing bytes to write.- Returns:
- the number of bytes actually written.
- Throws:
AsynchronousCloseException- if this channel is closed by another thread during this write operation.ClosedByInterruptException- if another thread interrupts the calling thread while this operation is in progress. The interrupt state of the calling thread is set and the channel is closed.ClosedChannelException- if this channel is closed.IOException- if another I/O error occurs.NotYetConnectedException- if this channel is not yet connected.- See Also:
GatheringByteChannel.write(java.nio.ByteBuffer[])
-