Please note that this documentation is not final and is subject to change.


DRAFT-b102

java.nio.channels
Class SocketChannel

java.lang.Object
  extended by java.nio.channels.spi.AbstractInterruptibleChannel
      extended by java.nio.channels.SelectableChannel
          extended by java.nio.channels.spi.AbstractSelectableChannel
              extended by java.nio.channels.SocketChannel
All Implemented Interfaces:
Closeable, ByteChannel, Channel, GatheringByteChannel, InterruptibleChannel, NetworkChannel, ReadableByteChannel, ScatteringByteChannel, WritableByteChannel

public abstract class SocketChannel
extends AbstractSelectableChannel
implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel

A selectable channel for stream-oriented connecting sockets.

[revised]  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:

Option Name Description
SO_SNDBUF The size of the socket send buffer
SO_RCVBUF The size of the socket receive buffer
SO_KEEPALIVE Keep connection alive
SO_REUSEADDR Re-use address
SO_LINGER Linger on close if data is present (when configured in blocking mode only)
TCP_NODELAY Disable the Nagle algorithm
Additional (implementation specific) options may also be supported.

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
Modifier Constructor and Description
protected SocketChannel(SelectorProvider provider)
          Initializes a new instance of this class.
 
Method Summary
Modifier and Type Method and Description
 SocketChannel bind(SocketAddress local)
          Binds the channel's socket to a local address.
abstract  boolean connect(SocketAddress remote)
          Connects this channel's socket.
abstract  boolean finishConnect()
          Finishes the process of connecting a socket channel.
 SocketAddress getLocalAddress()
          Returns the socket address that this channel's socket is bound to, or null if the socket is not bound.
<T> T
getOption(SocketOption<T> name)
          Returns the value of a socket option.
 SocketAddress getRemoteAddress()
          Returns the remote address to which this channel's socket is connected.
abstract  boolean isConnected()
          Tells whether or not this channel's network socket is connected.
abstract  boolean isConnectionPending()
          Tells whether or not a connection operation is in progress on this channel.
static SocketChannel open()
          Opens a socket channel.
static SocketChannel open(SocketAddress remote)
          Opens a socket channel and connects it to a remote address.
abstract  int read(ByteBuffer dst)
           
 long read(ByteBuffer[] dsts)
           
abstract  long read(ByteBuffer[] dsts, int offset, int length)
           
<T> SocketChannel
setOption(SocketOption<T> name, T value)
          Sets the value of a socket option.
 SocketChannel shutdownInput()
          Shutdown the connection for reading without closing the channel.
 SocketChannel shutdownOutput()
          Shutdown the connection for writing without closing the channel.
abstract  Socket socket()
          Retrieves a socket associated with this channel.
 Set<SocketOption<?>> supportedOptions()
          Returns a set of the socket options supported by this channel.
 int validOps()
          Returns an operation set identifying this channel's supported operations.
abstract  int write(ByteBuffer src)
           
 long write(ByteBuffer[] srcs)
           
abstract  long write(ByteBuffer[] srcs, int offset, int length)
           
 
Methods inherited from class java.nio.channels.spi.AbstractSelectableChannel
blockingLock, configureBlocking, implCloseChannel, implCloseSelectableChannel, implConfigureBlocking, isBlocking, isRegistered, keyFor, provider, register
 
Methods inherited from class java.nio.channels.SelectableChannel
register
 
Methods inherited from class java.nio.channels.spi.AbstractInterruptibleChannel
begin, close, end, isOpen
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.nio.channels.Channel
close, isOpen
 

Constructor Detail

SocketChannel

protected SocketChannel(SelectorProvider provider)
Initializes a new instance of this class.

Method Detail

open

public static SocketChannel open()
                          throws IOException
Opens a socket channel.

The new channel is created by invoking the openSocketChannel method of the system-wide default SelectorProvider object.

Returns:
A new socket channel
Throws:
IOException - If an I/O error occurs

open

public static SocketChannel open(SocketAddress remote)
                          throws IOException
Opens a socket channel and connects it to a remote address.

This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting socket channel, passing it remote, and then returning that channel.

Parameters:
remote - The remote address to which the new channel is to be connected
Throws:
AsynchronousCloseException - If another thread closes this channel while the connect operation is in progress
ClosedByInterruptException - 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 status
UnresolvedAddressException - If the given remote address is not fully resolved
UnsupportedAddressTypeException - If the type of the given remote address is not supported
SecurityException - If a security manager has been installed and it does not permit access to the given remote endpoint
IOException - 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:
validOps in class SelectableChannel
Returns:
The valid-operation set

bind

public SocketChannel bind(SocketAddress local)
                   throws IOException
Binds the channel's socket to a local address.

This method should be overridden. The default implementation of this method invokes the socket bind method.

Specified by:
bind in interface NetworkChannel
Parameters:
local - The address to bind the socket, or null to 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 channel
AlreadyBoundException - If the socket is already bound
UnsupportedAddressTypeException - If the type of the given address is not supported
ClosedChannelException - If the channel is closed
IOException - If some other I/O error occurs
Since:
1.7
See Also:
NetworkChannel.getLocalAddress()

getLocalAddress

public SocketAddress getLocalAddress()
                              throws IOException
Returns the socket address that this channel's socket is bound to, or null if the socket is not bound.

This method should be overridden. The default implementation of this method invokes the socket getLocalSocketAddress method.

Specified by:
getLocalAddress in interface NetworkChannel
Returns:
The socket address that the socket is bound to, or null if the channel's socket is not bound
Throws:
ClosedChannelException - If the channel is closed
IOException - If an I/O error occurs
Since:
1.7

setOption

public <T> SocketChannel setOption(SocketOption<T> name,
                                   T value)
                        throws IOException
Sets the value of a socket option.

This method should be overridden. The default implementation of this method only supports the socket options defined above.

Specified by:
setOption in interface NetworkChannel
Parameters:
name - The socket option
value - The value of the socket option. A value of null may be a valid value for some socket options.
Returns:
This channel
Throws:
UnsupportedOperationException - If the socket option is not supported by this channel
IllegalArgumentException - If the value is not a valid value for this socket option
ClosedChannelException - If this channel is closed
IOException - If an I/O error occurs
Since:
1.7
See Also:
StandardSocketOption

getOption

public <T> T getOption(SocketOption<T> name)
            throws IOException
Returns the value of a socket option.

This method should be overridden. The default implementation of this method only supports the socket options defined above.

Specified by:
getOption in interface NetworkChannel
Parameters:
name - The socket option
Returns:
The value of the socket option. A value of null may be a valid value for some socket options.
Throws:
UnsupportedOperationException - If the socket option is not supported by this channel
ClosedChannelException - If this channel is closed
IOException - If an I/O error occurs
Since:
1.7
See Also:
StandardSocketOption

supportedOptions

public Set<SocketOption<?>> supportedOptions()
Returns a set of the socket options supported by this channel.

This method should be overridden. The default implementation of this method returns a set containing only the socket options defined above.

Specified by:
supportedOptions in interface NetworkChannel
Returns:
A set of the socket options supported by this channel
Since:
1.7

shutdownInput

public SocketChannel shutdownInput()
                            throws IOException
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.

This method should be overridden. The default implementation of this method invokes the socket shutdownInput method.

Returns:
The channel
Throws:
NotYetConnectedException - If this channel is not yet connected
ClosedChannelException - If this channel is closed
IOException - If some other I/O error occurs
Since:
1.7

shutdownOutput

public SocketChannel shutdownOutput()
                             throws IOException
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.

This method should be overridden. The default implementation of this method invokes the socket shutdownOutput method.

Returns:
The channel
Throws:
NotYetConnectedException - If this channel is not yet connected
ClosedChannelException - If this channel is closed
IOException - If some other I/O error occurs
Since:
1.7

socket

public abstract Socket socket()
Retrieves a socket associated with this channel.

The returned object will not declare any public methods that are not declared in the Socket class.

Returns:
A socket associated with this channel

isConnected

public abstract boolean isConnected()
Tells whether or not this channel's network socket is connected.

Returns:
true if, and only if, this channel's network socket is open and connected

isConnectionPending

public abstract boolean isConnectionPending()
Tells whether or not a connection operation is in progress on this channel.

Returns:
true if, and only if, a connection operation has been initiated on this channel but not yet completed by invoking the finishConnect method

connect

public abstract boolean connect(SocketAddress remote)
                         throws IOException
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 returns false and the connection operation must later be completed by invoking the finishConnect method.

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 Socket class. That is, if a security manager has been installed then this method verifies that its checkConnect method 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:
true if a connection was established, false if this channel is in non-blocking mode and the connection operation is in progress
Throws:
AlreadyConnectedException - If this channel is already connected
ConnectionPendingException - If a non-blocking connection operation is already in progress on this channel
ClosedChannelException - If this channel is closed
AsynchronousCloseException - If another thread closes this channel while the connect operation is in progress
ClosedByInterruptException - 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 status
UnresolvedAddressException - If the given remote address is not fully resolved
UnsupportedAddressTypeException - If the type of the given remote address is not supported
SecurityException - If a security manager has been installed and it does not permit access to the given remote endpoint
IOException - If some other I/O error occurs

finishConnect

public abstract boolean finishConnect()
                               throws IOException
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 connect method. 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 appropriate IOException to 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 return false if 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 return true or 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:
true if, 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 initiated
ClosedChannelException - If this channel is closed
AsynchronousCloseException - If another thread closes this channel while the connect operation is in progress
ClosedByInterruptException - 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 status
IOException - If some other I/O error occurs

getRemoteAddress

public SocketAddress getRemoteAddress()
                               throws IOException
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.

This method should be overridden. The default implementation of this method invokes the socket getRemoteSocketAddress method.

Returns:
The remote address; null if the channel's socket is not connected
Throws:
ClosedChannelException - If the channel is closed
IOException - If an I/O error occurs
Since:
1.7

read

public abstract int read(ByteBuffer dst)
                  throws IOException
Specified by:
read in interface ReadableByteChannel
Throws:
NotYetConnectedException - If this channel is not yet connected
IOException

read

public abstract long read(ByteBuffer[] dsts,
                          int offset,
                          int length)
                   throws IOException
Specified by:
read in interface ScatteringByteChannel
Throws:
NotYetConnectedException - If this channel is not yet connected
IOException

read

public final long read(ByteBuffer[] dsts)
                throws IOException
Specified by:
read in interface ScatteringByteChannel
Throws:
NotYetConnectedException - If this channel is not yet connected
IOException

write

public abstract int write(ByteBuffer src)
                   throws IOException
Specified by:
write in interface WritableByteChannel
Throws:
NotYetConnectedException - If this channel is not yet connected
IOException

write

public abstract long write(ByteBuffer[] srcs,
                           int offset,
                           int length)
                    throws IOException
Specified by:
write in interface GatheringByteChannel
Throws:
NotYetConnectedException - If this channel is not yet connected
IOException

write

public final long write(ByteBuffer[] srcs)
                 throws IOException
Specified by:
write in interface GatheringByteChannel
Throws:
NotYetConnectedException - If this channel is not yet connected
IOException


DRAFT-b102