Java Socket Read returns Strange Characters on second read

445 Views Asked by At

I've got a C++ Socket Server that sends a JSON String to a Java Client. For the Java Part I'm using the following Code:

BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));    
while((inString = in.readLine()) != null) {
          Log.i("JSON", inString);

C++ Code:

WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;

if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return false; }

if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { return false; }

server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(13377);

if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) { return false; }

listen(s, 3);

c = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr *)&client, &c);
if (new_socket == INVALID_SOCKET) { return false; }

while (listenSocket) {
    if(...){
        char sendData[] = "hallo";
        send(new_socket, sendData, sizeof(sendData), NULL); 
    }

When receiving the First Time everything is received as planned. However, the second time It only prints out Questions Marks in Squares "�". Is that because I'm sending a char array of 2048 chars that might only contain a lower amount than that or what could the problem be?

2

There are 2 best solutions below

0
xander On

I think you should not send unnecessary data either way, so in your case only send the string with the following \0 or better and usually the default way the length of bytes and after that the data without \0 and only read a single string not a complete line.

Also be aware of the byte order (litte or big endian) when reading an integer as the data size for example.

I'm sure there is more documentation about how Java expects strings to be encoded for a socket connection or you have to read the raw bytes and convert it to a Java string yourself.

0
user207421 On

You are reading lines, i.e. character data terminated by \n, \r, or \r\n, as specified for BufferedReader.readLine(), but what you are sending isn't lines, it is null-terminated C strings. So you won't receive anything at all until the sender closes the connection, and then you will get a string containing who knows what where the nulls were.

You also aren't error-checking the result of send().