A selectable channel for stream-oriented connecting sockets.

Socket channels are not a complete abstraction of connecting network sockets. Binding, shutdown, and the manipulation of socket options must be done through an associated java.net.Socket object obtained by invoking the socket method. It is not possible to create a channel for an arbitrary, pre-existing socket, nor is it possible to specify the java.net.SocketImpl object to be used by a socket associated with a socket channel.

A socket channel is created by invoking one of the open methods of this class. 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.

The input and output sides of a socket channel may independently be shut down without actually closing the channel. Shutting down the input side of a channel by invoking the shutdownInput method of an associated socket object will cause further reads on the channel to return -1, the end-of-stream indication. Shutting down the output side of the channel by invoking the shutdownOutput method of an associated socket object will cause further writes on the channel to throw a ClosedChannelException .

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 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.

@author
Mark Reinhold
@author
JSR-51 Expert Group
@version
1.33, 03/12/19
@since
1.4
Closes this channel.

If the channel has already been closed then this method returns immediately. Otherwise it marks the channel as closed and then invokes the implCloseChannel method in order to complete the close operation.

Throws
IOException If an I/O error occurs
Adjusts this channel's blocking mode.

If the given blocking mode is different from the current blocking mode then this method invokes the implConfigureBlocking method, while holding the appropriate locks, in order to change the mode.

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 java.net.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
Return
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
Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Parameters
objthe reference object with which to compare.
Return
true if this object is the same as the obj argument; false otherwise.
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 java.io.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.

Return
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
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Return
a hash code value for this object.
Tells whether or not this channel's network socket is connected.

Return
true if, and only if, this channel's network socket is connected
Tells whether or not a connection operation is in progress on this channel.

Return
true if, and only if, a connection operation has been initiated on this channel but not yet completed by invoking the {@link #finishConnect finishConnect} method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Opens a socket channel.

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

Return
A new socket channel
Throws
IOException If an I/O error occurs
Opens a socket channel and connects it to a remote address.

This convenience method works as if by invoking the 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
Returns the provider that created this channel.
Return
The provider that created this channel
Throws
NotYetConnectedException If this channel is not yet connected
Reads 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 invocation

 c.read(dsts, 0, srcs.length);
Parameters
dsts The buffers into which bytes are to be transferred
Return
The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream
Throws
NonReadableChannelException If this channel was not opened for reading
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the read operation is in progress
ClosedByInterruptException 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 status
IOException If some other I/O error occurs
Reads 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,

 dsts[offset].remaining()
     + dsts[offset+1].remaining()
     + ... + dsts[offset+length-1].remaining()
at the moment that this method is invoked.

Suppose that a byte sequence of length n is read, where 0 <= n <= r. Up to the first dsts[offset].remaining() bytes of this sequence are transferred into buffer dsts[offset], up to the next dsts[offset+1].remaining() bytes are transferred into buffer dsts[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.

Parameters
dsts The buffers into which bytes are to be transferred
offset The offset within the buffer array of the first buffer into which bytes are to be transferred; must be non-negative and no larger than dsts.length
length The maximum number of buffers to be accessed; must be non-negative and no larger than dsts.length - offset
Return
The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream
Throws
IndexOutOfBoundsException If the preconditions on the offset and length parameters do not hold
NonReadableChannelException If this channel was not opened for reading
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the read operation is in progress
ClosedByInterruptException 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 status
IOException If some other I/O error occurs
Registers this channel with the given selector, returning a selection key.

An invocation of this convenience method of the form

sc.register(sel, ops)
behaves in exactly the same way as the invocation
sc.register (sel, ops, null)
Parameters
sel The selector with which this channel is to be registered
ops The interest set for the resulting key
Return
A key representing the registration of this channel with the given selector
Throws
ClosedChannelException If this channel is closed
IllegalBlockingModeException If this channel is in blocking mode
IllegalSelectorException If this channel was not created by the same provider as the given selector
CancelledKeyException If this channel is currently registered with the given selector but the corresponding key has already been cancelled
IllegalArgumentException If a bit in ops does not correspond to an operation that is supported by this channel, that is, if set & ~validOps() != 0
Registers this channel with the given selector, returning a selection key.

This method first verifies that this channel is open and that the given initial interest set is valid.

If this channel is already registered with the given selector then the selection key representing that registration is returned after setting its interest set to the given value.

Otherwise this channel has not yet been registered with the given selector, so the register method of the selector is invoked while holding the appropriate locks. The resulting key is added to this channel's key set before being returned.

Retrieves a socket associated with this channel.

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

Return
A socket associated with this channel
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 
Return
a string representation of the object.
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 ).

Return
The valid-operation set
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Throws
NotYetConnectedException If this channel is not yet connected
Writes 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 invocation

 c.write(srcs, 0, srcs.length);
Parameters
srcs The buffers from which bytes are to be retrieved
Return
The number of bytes written, possibly zero
Throws
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the write operation is in progress
ClosedByInterruptException 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 status
IOException If some other I/O error occurs
Writes 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,

 srcs[offset].remaining()
     + srcs[offset+1].remaining()
     + ... + srcs[offset+length-1].remaining()
at the moment that this method is invoked.

Suppose that a byte sequence of length n is written, where 0 <= n <= r. Up to the first srcs[offset].remaining() bytes of this sequence are written from buffer srcs[offset], up to the next srcs[offset+1].remaining() bytes are written from buffer srcs[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.

Parameters
srcs The buffers from which bytes are to be retrieved
offset The offset within the buffer array of the first buffer from which bytes are to be retrieved; must be non-negative and no larger than srcs.length
length The maximum number of buffers to be accessed; must be non-negative and no larger than srcs.length - offset
Return
The number of bytes written, possibly zero
Throws
IndexOutOfBoundsException If the preconditions on the offset and length parameters do not hold
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the write operation is in progress
ClosedByInterruptException 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 status
IOException If some other I/O error occurs