uriel
uriel

Reputation: 1248

Server/client in java and c/objective - Encoding issues

I'm trying to write simple code for server/client.

The server (in java) wait for string from client:

ServerSocket ss = new ServerSocket(4001);
Socket s = ss.accept() ;

DataInputStream dataStreamIn = new DataInputStream(s.getInputStream()) ;

byte buffer[] = new byte[100];

dataStreamIn.read(buffer);


if((new String(buffer)).equals("1"))
    System.out.print("yes");//never printed

the client (objective-c) send string to server:

uint8_t buffer[1000] ={0};
sprintf((char*)buffer,"%s", "1");

NSInteger wrote = [self.networkStreamOut 
                   write:buffer 
                   maxLength:(uint8_t)strlen((char *)buffer)];

The problem is the buffer on server is indeed "1" BUT when I'm trying to compare with .equals() it return false!

EDIT:

When I'm tring to add to server this line:

System.out.println(Integer.valueOf(new String(buffer))) ;

I'm getting this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1

Upvotes: 0

Views: 449

Answers (1)

Perception
Perception

Reputation: 80633

You should explicitly state what encoding you expect your incoming data to be in, on both the client and server side. This is especially important to do when communicating between different platforms/languages.

But, of course, that's not what your problem is - your string is getting created with a bunch of non-printing characters because you allocated it with the entire byte array:

byte[] buffer = new byte[100];
new String(buffer);

Presumably the buffer is not completely filled after you read data into it, and the defaulted zero values in it are getting converted in your string into non-printing characters. You can validate this by printing the length of the string you created, you will find it to be greater than 1.

You have two remedies - either trim() the String before comparing its value, or keep track of the number of actual bytes read and create a new byte array of the correct length (before creating your String).

Upvotes: 1

Related Questions