简体   繁体   中英

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

I try to communicate with a java application to a µController in wifi (Flyport).

I have a problem with the java application : It first create a socket to communicate with the Flyport server, then send a message and receive the Flyport answer.

Everything work fine until the read part. I'm polling the read() function of the BufferedReader until it return -1, but it doesn't. The first read works fine, all the answer are red, but the application stay stuck when it tries to read again.

My code is very simple : Java application :

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
}

The code in the 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));
}

The java application read msg and msg2 with the first read(). msg and msg2 have "\\r\\n" at the end.

Doesn't somebody can tell me where I am wrong ? Is there a function from BufferedReading that tells how much data there is left to read ?

Thanks and regards.

NB : I try with a small buffer in the java application, the problem is the same, read() is stuck when there is nothing left to read...

You're reading from the socket until end of stream, and you're never causing end of stream, as you are never closing the socket at the sender. Either close the socket or don't read until end of stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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