1

I am making a server client system in which the client will write a message to the server and the server will save it as a string and print it in the console. But when ever the System tries to read the line I get "PrintStream error" in the console. No errors or anything. I am reading the string, on the server, with:

DataInputStream inFromClient = new DataInputStream(socket.getInputStream());
String connectReason = inFromClient.readUTF();

And I am sending the string from the client like this:

clientSocket = new TcpClient(Host, Port);
Stream = clientSocket.GetStream(); 
outToServer = new StreamWriter(Stream);

Why am I getting that error? They connect without error and when I get to that line I get the "PrintStream Error".

Alex
  • 13
  • 2
  • 1
    What '`PrintStream` error'? Stack trace? The problem is that `readUTF()` only understands data written by `writeUTF().` – user207421 Jun 05 '15 at 02:11

1 Answers1

0

The readUTF() method expects the data to be formatted in a specific way ( more details here ), the data send by what looks like a C# program is not formatted in a way that can be interpreted correctly by the readUTF() method.

You can read the raw bytes from the socket's input stream and convert those to a String, eg:

try(InputStream in = socket.getInputStream()){
     byte[] b = new byte[1024];
     String msg = "";
     for(int r;(r = in.read(b,0,b.length))!=-1;){
        msg += new String(b,0,r,"UTF-8");
     }
     System.out.println("Message from the client: " + msg);
}catch (Exception e) {
    e.printStackTrace();
}

Replace "UTF-8" with the charset that the C# program uses.

Titus
  • 22,031
  • 1
  • 23
  • 33
  • Ok, how can I fix that. What do I change to make it readable? – Alex Jun 05 '15 at 01:49
  • Yes the Client is in C# and the server is Java. – Alex Jun 05 '15 at 01:53
  • @Alex I've included a solution in my answer, the downside of this approach is that you can use the `String` send by the client only after it disconnects. – Titus Jun 05 '15 at 01:58
  • If the program that uses C# is Unity3D and MonoDevelop, would might it be other than UTF-8? And why can't I use the string until after the client disconnects? – Alex Jun 05 '15 at 02:10
  • @Alex The encoding depends on the system, The `for` loop blocks until the client disconnects, if you want to use the received that before then, you need to add some logic in the loop to check if all the necessary data was received. – Titus Jun 05 '15 at 02:22