我正在使用非阻塞serversocket。我已将ByteArray的大小分配为100.然后,客户端向服务器发送200字节大小的数据,服务器接收200字节消息为100字节+ 100字节数据。我的问题是,在读取100字节后来自频道,其中存储剩余的100字节数据,直到再次调用read()。谢谢(对不起任何语法错误)
服务器程序:
public class SelectorExample {
public static void main (String [] args)
throws IOException {
// Get selector
Selector selector = Selector.open();
System.out.println("Selector open: " + selector.isOpen());
// Get server socket channel and register with selector
ServerSocketChannel serverSocket = ServerSocketChannel.open();
InetSocketAddress hostAddress = new
InetSocketAddress("131.10.20.16", 5454);
serverSocket.socket().bind(hostAddress,0);
serverSocket.configureBlocking(false);
int ops = serverSocket.validOps();
SelectionKey selectKy = serverSocket.register(selector, ops, null);
for (;;) {
System.out.println("Waiting for select...");
int noOfKeys = selector.select();
System.out.println("Number of selected keys: " + noOfKeys);
Set selectedKeys = selector.selectedKeys();
Iterator iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey ky = (SelectionKey)iter.next();
if (ky.isAcceptable()) {
// Accept the new client connection
SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
// Add the new connection to the selector
client.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted new connection from client: " + client);
}
else if (ky.isReadable()) {
// Read the data from client
SocketChannel client = (SocketChannel) ky.channel();
ByteBuffer buffer = ByteBuffer.allocate(100);
int i =client.read(buffer);
String output = new String(buffer.array());
System.out.println("Message read from client: " + output);
if (i == -1) {
client.close();
System.out.println("Client messages are complete; close.");
}
} // end if (ky...)
iter.remove();
} // end while loop
} // end for loop
}