TechNewb
TechNewb

Reputation: 59

TCP Bytearray doesnt work, but Printerwriter works?

Currently I'm trying to communicate between from Client to Server and vice versa in Java.

So as of now, I tried with the following

Attempt 1) Trying to send through string in bytearray form.

Client

OutputStream os = clientSock.getOutputStream();
byte[] sndMsg = new String("test").getBytes();
os.write(sndMsg);
os.flush();

Server

InputStream is = serverChild.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

String rcvRequest = br.readLine();
System.out.println(rcvRequest);

Apparently when it does not print out test.

Attempt 2) However, when I change the code from Client side to

PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSock.getOutputStream()));
out.println("test");
out.flush();

It works. Why is this so? Is it any way I can use attempt 1 to try and send byte array over and receive it as a string in the server side? Thank you.

Upvotes: 1

Views: 25

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

BufferedReader.readLine waits for NewLine character, you should add it to "test" in attempt 1. println in attempt 2 adds it automatically

Upvotes: 1

Related Questions