Sending message using non-blocking I/O in java(NIO API)

若如初见. 提交于 2020-05-24 05:00:06

问题


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("\nData read.");
buffer.flip();
int usedBytes = buffer.position();
byte[] bufferArray = buffer.array();
String message = new String(bufferArray, 0, usedBytes);
displayArea.append("\n"+message);

And this is a piece of client code:

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.


回答1:


You need to flip() before write(), and compact() afterwards.

NB Looping while read() returns -1 doesn't begin to make sense. It means the peer disconnected, for heaven's sake.



来源:https://stackoverflow.com/questions/26072926/sending-message-using-non-blocking-i-o-in-javanio-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!