在java中使用非阻塞I/O发送消息(NIO API) [英] Sending message using non-blocking I/O in java(NIO API)

查看:30
本文介绍了在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.

这篇关于在java中使用非阻塞I/O发送消息(NIO API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆