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

查看:160
本文介绍了使用Java(NIO API)中的非阻塞I/O发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个服务器/客户端程序,客户端向服务器发送文本消息.我使用了非阻塞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("\nData read.");
buffer.flip();
int usedBytes = buffer.position();
byte[] bufferArray = buffer.array();
String message = new String(bufferArray, 0, usedBytes);
displayArea.append("\n"+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.

推荐答案

您需要flip()write()之前,然后在compact()之后.

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

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(NIO API)中的非阻塞I/O发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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