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".
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.