我正在尝试编写一个程序,该程序接受java nio套接字通道连接,但也使它们保持打开状态。因此,假设客户端发送了一条消息,那么服务器是否应该立即发送相同的消息(简单回显服务器),但应答过程不起作用。如果客户端发送新消息,服务器将不会响应,直到我关闭客户端的套接字通道。但是,在我关闭客户端的频道后,所有先前发送的消息将一次性进入。(抱歉我的英语不好,这不是我的母语)
写入过程用于服务器端和客户端。
写作过程:
try {
final ByteBuffer byteBuffer = ByteBuffer.wrap(data);
while(byteBuffer.hasRemaining()){
socketChannel.write(byteBuffer);
}
byteBuffer.flip();
} catch (IOException exception) {
throw new BloumException(exception.getMessage());
}
阅读过程:
final ByteBuffer byteBuffer = ByteBuffer.allocate(DefaultConnectionCreator.this.getDefaultBufferSize());
try {
while(socketChannel.read(byteBuffer) != -1){
//byteBuffer.clear();
}
} catch (IOException exception) {
exception.printStackTrace();
throw new BloumException(exception.getMessage());
}
return byteBuffer.array();
关键选择过程(自动关闭返回假):
private void handleKeys(final ServerSocketChannel serverSocketChannel, Set<SelectionKey> keys, HashMap<SocketChannel, ByteBuilder> sessions) throws Exception{
final Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()){
final SelectionKey selectionKey = iterator.next();
iterator.remove();
if(selectionKey.isValid()){
if(selectionKey.isAcceptable()){
final ServerSocketChannel serverSocketChannel2 = (ServerSocketChannel)selectionKey.channel();
final SocketChannel socketChannel = serverSocketChannel2.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ);
sessions.put(socketChannel, new ByteBuilder());
}
}
}
繁花如伊
相关分类