在java中使用非阻塞I/O发送消息(NIO API)
我正在编写一个服务器/客户端程序,客户端将文本消息发送到服务器.我使用了非阻塞 I/O (NIO API),但服务器上的消息无法正确显示.这是我在服务器上的代码:
I'm writing a server/client program that clients send text message to server.I have used non-blocking I/O (NIO API) but messages on the server do not display correctly.this is my code on server:
private JTextArea displayArea;
private int numBytes;
private ByteBuffer buffer;
/*...
some code is here
...*/
displayArea = new JTextArea();
add(new JScrollPane(displayArea), BorderLayout.CENTER);
setSize(400, 500);
setVisible(true);
/*...
some code is here
...*/
buffer = ByteBuffer.allocate(20);
buffer.clear();
displayArea.append("reading data...");
do{
numBytes = socketChannel.read(buffer);
}while(numBytes == -1);
displayArea.append("
Data read.");
buffer.flip();
int usedBytes = buffer.position();
byte[] bufferArray = buffer.array();
String message = new String(bufferArray, 0, usedBytes);
displayArea.append("
"+message);
这是一段客户端代码:
byte[] byteData = message.getBytes();
buffer.put(byteData);
socketChannel.write(buffer);
buffer.clear();
在客户端向服务器发送消息的运行时,会显示空格字符或一条消息.
In run time when a client send message to server , space characters or a piece of message is shown.
推荐答案
需要在write()
之前flip()
,compact()
之后.
NB 循环而 read()
返回 -1 开始没有意义.看在上帝的份上,这意味着对等方已断开连接.
NB Looping while read()
returns -1 doesn't begin to make sense. It means the peer disconnected, for heaven's sake.
相关文章