我在客户端服务器Java应用程序中使用SocketChannel遇到问题。
首先,在服务器中,我初始化选择器:
Selector selector = null;
try{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(5000));
serverSocketChannel.configureBlocking(false);
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch(IOException e){
e.printStackTrace();
return;
}
然后我开始一会儿:
while(true) {
try {
selector.select();
} catch (IOException ex) {
ex.printStackTrace();
break;
}
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
try {
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel clientChannel = server.accept();
clientChannel.configureBlocking(false);
clientChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
readFunction((SocketChannel)key.channel())
}
}
}
现在我应该开发readFunction。我想在客户端和服务器之间使用字符串(Json)发送数据,但是由于它们没有阻塞,所以我不知道是否可以在不发送字符串大小的情况下做到这一点。
有人可以帮我吗?