java.nio.channels.SocketChannel

public abstract class
SocketChannel
extends AbstractSelectableChannel
implements ByteChannel GatheringByteChannel ScatteringByteChannel
java.lang.Object
? java.nio.channels.spi.AbstractInterruptibleChannel
? java.nio.channels.SelectableChannel
? java.nio.channels.spi.AbstractSelectableChannel
? java.nio.channels.SocketChannel

Class Overview

SocketChannel是一个可选的通道,通道提供一个连接socket的局部抽象流。
socket()方法返回相关的socket实例。
当使用open()方法打开channel时,socket channel处于打开但并未连接状态。
当调用connect(SocketAddress)方法建立连接后,通道将一直连接着直到被关闭。
如果连接对象connection没有被锁定,可以用connect(SocketAddress) 来初始化connection对象,然后用finishConnect()进行建立连接的最后一步。
isConnectionPending()可以查看连接对象是否被锁住。isConnected()可以查看是否连接到socket了。
channel的输入端和输出端可以被独立地、异步地关闭,而不需要关闭channel。
shutdownInput方法用于channel的输入端,因此读操作返回-1,也就是流的结束。
shutdownInput方法用于channel的输入端,读操作返回-1,也就是流的结束。
如果另外一个线程正在进行读操作,这时候发生了shutdown事件,读操作将被终止并返回流的结束。
shutdownOutput方法用于channel的输出端。
此时如果另外一个线程正在进行写读操作,則会抛出ClosedChannelException异常.
而如果输出流被關閉,此时有线程在进行写操作,那么会抛出AsynchronousCloseException异常.
注意,Socket是线程安全的.也就是说任一时刻,不能有多于一条线程在进行读或著写操作.
connect(SocketAddress)和finishConnect() 方法是同步互斥的,所以当这两个方法正在执行时,
读写操作将被挂起.

Summary

Protected Constructors

SocketChannel(SelectorProvider selectorProvider)
Constructs a new SocketChannel.
构造一个新的SocketChannel。

Public Methods

abstract boolean connect(SocketAddress address)
Connects this channel's socket with a remote address.
将channel与远程地址相连。

abstract boolean finishConnect()
Completes the connection process initiated by a call of connect(SocketAddress).
connect(socketAddress)方法建立链接,由该方法完成。

abstract boolean isConnected()
Indicates whether this channel's socket is connected.
判断链接是否已经建立。

abstract boolean isConnectionPending()
Indicates whether this channel's socket is still trying to connect.
判断channel的socket是否仍在尝试建立连接。

static SocketChannel open()
Creates an open and unconnected socket channel.
创建一个打开但是未连接的socket channel。

static SocketChannel open(SocketAddress address)
Creates a socket channel and connects it to a socket address.
创建一个socket channel并连接到指定的远程地址。

abstract int read(ByteBuffer target)
Reads bytes from this socket channel into the given buffer.
从socket channel读取数据到指定的缓冲区。

abstract long read(ByteBuffer[] targets, int offset, int length)
Reads bytes from this socket channel into a subset of the given buffers.
从socket channel的offset处读取length个字节,存储到targets。

synchronized final long read(ByteBuffer[] targets)
Reads bytes from this socket channel and stores them in the specified array of buffers.
从socket channel读取字节数据,存储到指定的缓冲区数组。

abstract Socket socket()
Returns the socket assigned to this channel, which does not declare any public methods that are not declared in Socket.
返回分配给该channel的socket。

final int validOps()
Gets the valid operations of this channel.
返回可用操作。

/* 写操作与读操作类似,不赘述。 */
synchronized final long write(ByteBuffer[] sources)
Writes bytes from all the given byte buffers to this socket channel.

abstract long write(ByteBuffer[] sources, int offset, int length)
Attempts to write a subset of the given bytes from the buffers to this socket channel.

abstract int write(ByteBuffer source)
Writes bytes from the given byte buffer to this socket channel.

[Expand]
Inherited Methods
From class java.nio.channels.spi.AbstractSelectableChannel
From class java.nio.channels.SelectableChannel
From class java.nio.channels.spi.AbstractInterruptibleChannel
From class java.lang.Object
From interface java.io.Closeable
From interface java.nio.channels.Channel
From interface java.nio.channels.GatheringByteChannel
From interface java.nio.channels.InterruptibleChannel
From interface java.nio.channels.ReadableByteChannel
From interface java.nio.channels.ScatteringByteChannel
From interface java.nio.channels.WritableByteChannel

Protected Constructors

protected SocketChannel (SelectorProvider selectorProvider)
Since: API Level 1
Constructs a new SocketChannel.
Parameters
selectorProvider an instance of SelectorProvider.


Public Methods

public abstract boolean connect (SocketAddress address)
Since: API Level 1
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 occurrs. If the channel is non-blocking, this method will return true if the connection is finished at once or return false when the connection must be finished later by calling finishConnect().
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 Socket class.
将channel连接到远程地址。
如果channel被阻塞了。该方法将被挂起指定连接完成或者出现IO异常。
如果channel没有被阻塞,当连接完成时方法返回true;如果需要调用finishConnect()方法完成连接,则返回false。
该方法可以在任何时刻被调用,并且在进行连接时会阻塞所有读和写操作。
它执行的安全检查与connect方法相同。

Parameters
address the address to connect with.
Returns
true if the connection is finished, false otherwise.
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.
SecurityException if there is a security manager and it denies the access of address.
IOException if an I/O error occurs.

public abstract boolean finishConnect ()
Since: API Level 1
Completes the connection process initiated by a call of connect(SocketAddress).
This method returns true if the connection is finished already and returns false if 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 true when 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 read and write operations while connecting.
该方法返回true,如果连接已经完成了;返回false,如果channel处于非阻塞状态并且连接尚未建立。
如果channel处于阻塞模式,该方法将被挂起;在完成连接后返回true。如果连接失败,则关闭channel并且抛出异常。
该方法可以在任意时刻被调用,执行连接操作使会阻塞其它所有读和写操作。
Returns
true if the connection is successfully finished, false otherwise.
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.

public abstract boolean isConnected ()
Since: API Level 1
Indicates whether this channel's socket is connected.
Returns
true if this channel's socket is connected, false otherwise.

public abstract boolean isConnectionPending ()
Since: API Level 1
Indicates whether this channel's socket is still trying to connect.
Returns
true if the connection is initiated but not finished; false otherwise.
连接已经初始化但是未完成,返回true;
否则返回false。

public static SocketChannel open ()
Since: API Level 1
Creates an open and unconnected socket channel.
This channel is created by calling openSocketChannel() of the default SelectorProvider instance.
Returns
the new channel which is open but unconnected.
Throws
IOException if an I/O error occurs.

public static SocketChannel open (SocketAddress address)
Since: API Level 1
Creates a socket channel and connects it to a socket address.
This method performs a call to open() followed by a call to connect(SocketAdress).
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.
SecurityException if there is a security manager and it denies the access of address.
UnresolvedAddressException if the address is not resolved.
UnsupportedAddressTypeException if the address type is not supported.
IOException if an I/O error occurs.


/* 读写操作的详细文档请参照java.nio.channels.ServerSocketChannel.java */
public abstract int read (ByteBuffer target)
Since: API Level 1
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.
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
read(java.nio.ByteBuffer)

public abstract long read (ByteBuffer[] targets, int offset, int length)
Since: API Level 1
Reads bytes from this socket channel into a subset of the given buffers. This method attempts to read all remaining() bytes from length byte buffers, in order, starting at targets[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.
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 if offset < 0 or length < 0, or if offset + length is greater than the size of targets.
IOException if another I/O error occurs.
NotYetConnectedException if this channel is not yet connected.
See Also
read(java.nio.ByteBuffer[], int, int)

public final synchronized long read (ByteBuffer[] targets)
Since: API Level 1
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);
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.

public abstract Socket socket ()
Since: API Level 1
Returns the socket assigned to this channel, which does not declare any public methods that are not declared in Socket.
Returns
the socket assigned to this channel.
public final int validOps ()
Since: API Level 1
Gets the valid operations of this channel. Socket channels support connect, read and write operation, so this method returns SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE.
Returns
the operations supported by this channel.
See Also
validOps()

public final synchronized long write (ByteBuffer[] sources)
Since: API Level 1
Writes bytes from all the given byte buffers to this socket channel.
Calling this method is equivalent to calling write(sources, 0, sources.length);
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

write(java.nio.ByteBuffer[])
public abstract long write (ByteBuffer[] sources, int offset, int length)
Since: API Level 1
Attempts to write a subset of the given bytes from the buffers to this socket channel. This method attempts to write all remaining() bytes from length byte buffers, in order, starting at sources[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.
Parameters
sources the array of byte buffers that is the source for bytes written to this channel.
offset the index of the first buffer in buffers to 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 if offset < 0 or length < 0, or if offset + length is greater than the size of sources.
IOException if another I/O error occurs.
NotYetConnectedException if this channel is not yet connected.
See Also
write(java.nio.ByteBuffer[], int, int)

public abstract int write (ByteBuffer source)
Since: API Level 1
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.
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
write(java.nio.ByteBuffer)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值