问题
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