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?
I think you should not send unnecessary data either way, so in your case only send the string with the following
\0or better and usually the default way the length of bytes and after that the data without\0and 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.