这里有一台服务器和一台客户端.并且通过可选择的频道维持了通信.喜欢 - 服务器---
SelectionKey selectKey = channel.register(this.selector,
SelectionKey.OP_ACCEPT);
while (selectKey.selector().select() > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
ServerSocketChannel nextChannel = (ServerSocketChannel) key
.channel();
SocketChannel newChannel = nextChannel.accept();
newChannel.configureBlocking(false);
if (!newChannel.isRegistered()) {
SelectionKey selectionKey = newChannel.register(
this.selector, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);
selectionKey.attach(newChannel);
}
} else if (key.isWritable()) {
SocketChannel attachment1 = (SocketChannel)key.attachment();
ByteBuffer writeBuffer = ByteBuffer.wrap("Hello".getBytes());
attachment1.write(writeBuffer);
System.out.print("Written");
}
}
}
Run Code Online (Sandbox Code Playgroud)
客户:
InetSocketAddress isa = new InetSocketAddress(InetAddress
.getLocalHost(), 4444);
SocketChannel sc = null;
try {
while (true) {
Thread.sleep(10000);
sc = SocketChannel.open();
sc.connect(isa);
ByteBuffer byteBuffer = ByteBuffer.allocate(BUFSIZE);
int nbytes = sc.read(byteBuffer);
byteBuffer.flip();
dbuf.flip();
CharBuffer cb = decoder.decode(byteBuffer);
System.out.println(isa + " : " + cb);
}
Run Code Online (Sandbox Code Playgroud)
问题是每次客户端读取数据达到客户端缓冲区限制的全部大小而不是发送数据限制.
| 归档时间: |
|
| 查看次数: |
535 次 |
| 最近记录: |