【发布时间】:2014-08-12 09:49:17
【问题描述】:
我尝试通过 java 应用程序与 wifi (Flyport) 中的 µController 进行通信。
我的 java 应用程序有问题: 它首先创建一个套接字与 Flyport 服务器通信,然后发送消息并接收 Flyport 应答。
在阅读部分之前一切正常。我正在轮询 BufferedReader 的 read() 函数,直到它返回 -1,但它没有。第一次读取工作正常,所有答案都是红色的,但应用程序在尝试再次读取时会卡住。
我的代码很简单: Java 应用程序:
try (
Socket clientSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
)
{
...//Connection and sending message works fine
}
char[] buffer = new char[500];
while ((in.read(buffer)) != -1) { // first read() works fine, second read() stay stuck...
System.out.println(buffer); // display all answer sent by flyport
}
flyport 中的代码:
while(isClientConnected){
//check if client is still connected
...
//read client message
while((RxLen=TCPRxLen(sock))>0)
{
TCPRead(sock,bff,RxLen);
strcat(msg,bff);
}
//write back to the client that the order is received
TCPWrite(sock, msg, strlen(msg));
//process the client order
...
//Write to the client that the process is done
TCPWrite(sock, msg2, strlen(msg2));
}
java 应用程序使用第一个 read() 读取 msg 和 msg2。 msg 和 msg2 末尾有“\r\n”。
难道没有人能告诉我我哪里错了吗? BufferedReading 中是否有一个函数可以告诉您还有多少数据需要读取?
感谢和问候。
注意:我尝试在 java 应用程序中使用一个小缓冲区,问题是一样的,当没有什么可以读取时,read() 卡住了......
【问题讨论】:
-
您是否尝试过使用 while(in.ready()) 例如while (in.ready()) System.out.println(in.readLine());
-
@ThusithaThilinaDayaratne 为什么? available() 和 ready() 没有很多关键用途,这当然不是其中之一。
-
@EJP 因为那时 JVM 会为我们处理缓冲区,而不是我们手动处理缓冲区。不是更合适吗?
-
@ThusithaThilinaDayaratne 不,JVM 不会“为我们处理缓冲区”。你似乎不知道这个方法实际上做了什么。看看 Javadoc。
标签: java sockets tcp socket.io microcontroller