我尝试与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的末尾有"rn"。
没有人能告诉我我错在哪里吗?是否有BufferedReading的函数告诉我们还有多少数据要读?Thanks and regards.
NB:我尝试在java应用程序中使用一个小缓冲区,问题是相同的,read()在没有任何东西可读时卡住…
您正在从套接字读取直到流结束,并且您从未导致流结束,因为您从未在发送端关闭套接字。要么关闭套接字,要么直到流结束才读取。