Sending message using non-blocking I/O in java(NIO API)(在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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在java中使用非阻塞I/O发送消息(NIO API)
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- JPA惰性列表上的流 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
