繁体   English   中英

与TCP套接字和PIC的Java通信卡在read()中

[英]Java communication with TCP socket and PIC stuck in read()

我尝试通过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()卡住了。

您正在从套接字读取数据,直到流结束,而且也从未导致流结束,因为您从未关闭发送方的套接字。 关闭套接字,或者直到流结束才读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM