TCP Connection: Java + mbed

09 Feb 2011

Hey community :)

I'm trying to get a raw TCP/IP connection between my mbed and a simple server program written in Java running. Building up and closing the connection works fine, so does sending some text TO the mbed.

BUT...

Everytime i want to send a text from the mbed to my server the connection will be reset and an exception is thrown.

Can someone take look at my mbed code while I'm trying to find a way to upload the .java file? TCPTest

Thx

10 Feb 2011

Is the exception thrown on the mbed or in the Java application running on the PC?

I have noticed a few things in your string processing. In your onTCPSocketEvent() function, there is the following code

// Get the data and send them back to pc
char rxBuffer[128];
int len = socket.recv(rxBuffer, sizeof(rxBuffer));
printf("MESSAGE: %s", rxBuffer);

You might not get a NULL terminator in rxBuffer and this could lead to walking off the end of the string in printf. It would be better to pass socket.recv() the size of the buffer -1 to guarantee that you have room for a NULL terminator and then check that len is >= 0 and then set rxBuffer[len] = '\0' before calling printf.

// Get the data and send them back to pc
char rxBuffer[128];
int len = socket.recv(rxBuffer, sizeof(rxBuffer)-1);
if (len >= 0)
{
    rxBuffer[len] = '\0';
    printf("MESSAGE: %s", rxBuffer);
}
else
{
    printf("Recv Error\n");
}

I noticed that you don't send the NULL terminator from the mbed to your PC so maybe something similar is happening on the PC?

10 Feb 2011

Thx for the answer!

Quote:

Is the exception thrown on the mbed or in the Java application running on the PC?

The mbed code works fine, even receiving the text. But everytime my mbed sends some data the java application throws a exception.

Quote:

I noticed that you don't send the NULL terminator from the mbed to your PC so maybe something similar is happening on the PC?

Maybe. I'll try it out.

13 Feb 2011

I think you need to call Net::poll() after send, but before you close the socket. IIRC the send() call itself doesn't send the data itself, but the poll() call will do. Also, I think you need to wait for the TCP connection to be established after the socket.connect() call - when this function returns this might no be happened.