jeudi 22 novembre 2018

ESP8266 - client socket is getting closed after calling method readBytes

I'm trying to send message from my pc to the board, but problem is I keep losing connection before I decide to send message.

This is code from which I'm sending the message.I create socket, connect to board, and then wait for inputs from Scanner object.When I get some input I send message to board.

CLIENT

    Socket socket = new Socket();
    socket.connect(new InetSocketAddress("192.168.4.1",3000));
    Scanner in = new Scanner(System.in);
    String message = DataProtocol.sendMessageFormat("KLASA","METHOD","Message");
    String message1 = DataProtocol.sendMessageFormat("KLASA","METHOD","Message");
    message = message1 + message;
    OutputStream outputStream = socket.getOutputStream();

    String line;
    while(!(line = in.nextLine()).equals("EXIT")){
        outputStream.write(message.getBytes());
        outputStream.flush();
    }

This is code that is recv.message.

SERVER

void CommunicationProcessor::readFromStream(WiFiClient* wifiClient){
CLIENT_ACTIVE = true;

while(CLIENT_ACTIVE){
    Serial.println(wifiClient->connected()); -> returns 1
    int bytesRead = wifiClient->readBytes(buffer,1024); -> returns 0
    Serial.println(wifiClient->connected()); -> returns 0
    dataManager.appendData(bufferReader.getDataReaded(buffer,bytesRead));

    if (checkIfEndLine(bytesRead)){
        handleDataRecv();
        dataManager.clearBuffer();
    }
}
Serial.println("CLIENT QUIT");

}

Before method readBytes, I'call method connected() and it returns 1.So everything is fine. Method readBytes returns 0, because I did not yet sent any message. After that I call connected() one more time and this time it returns 0.

Now if I remove this Scanner object and loop from code and send message immediately, server will recv. message.

    Socket socket = new Socket();
    socket.connect(new InetSocketAddress("192.168.4.1",3000));
    Scanner in = new Scanner(System.in);
    String message = DataProtocol.sendMessageFormat("KLASA","METHOD","Message");
    String message1 = DataProtocol.sendMessageFormat("KLASA","METHOD","Message");
    message = message1 + message;
    OutputStream outputStream = socket.getOutputStream();
    outputStream.write(message.getBytes());
    outputStream.close();

My questions is why is connection closed after I' call method readBytes?

Aucun commentaire:

Enregistrer un commentaire