0

I'm trying to get a very simple Client-Server system to work, where the Client will send a String over to the Server, and the server will then store that String into a file.

The client sends the string through:

//Other Code

sockStrm = new DataOutputStream (clientSocket.getOutputStream ());

//Other code

sockStrm.writeChars (line);

//Other code

And the Server receives the String with:

//Other code 

strm = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ())); 

//Other code

stringLine = strm.readLine (); 

//Other code

When I send the string STOP, the length of the String is 4 on the client side, and on the server side the length of the String is 9 and displays as STOP

I've tried to substring the received String on the Server side, without luck.

Any pointers on how to deal with this?

1 Answer 1

3

Use symmetric methods:

DataOutputStream sockStrm =...
sockStrm.writeUTF(str);

and

DataInputStream sockStrm = ...
String str = sockStrm.readUTF();

writeChars writes individual characters as two byte values. Readers follow the encoding to reconstruct the string from a sequence of bytes, which will definitely not be according to high-byte-low-byte for each character code. Hence you get some mish-mash of zero bytes with the original low-byte values so you still have a glimpse of the original string value. Using \x00 to denote a NULL byte:

S-T-O-P => on the line: \x00-S-\x00-T-\x00-O-\x00-P => prints as STOP

Use a loop over the characters of the incoming string and display their integer values (str.charAt(i)) to see the above for yourself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.