javaprintwriterdatainputstreaminputstreamreader

DataInputStream printing unknown character from a socket


I'm getting an unknown character when reading from a socket using DataInputStream. When I send "Hello" on the server side the output is "Hello" the unknown character is the issue. I'm new to socket programming so I don't know what the issue could be. I tried using a BufferReader and PrintWriter too bu the server when using readLine() does not print the text sent but rather java.io.BufferedReader.

Server Side:

//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream is= new DataInputStream(socket.getInputStream());
String userinput= is.readLine();
System.out.println("Client message: "+userinput);

Client Side:

//BufferedReader std= new BufferedReader(new InputStreamReader(System.in));
String userInput;
DataOutputStream out;
while((userInput=std.readLine()) !=null){
    Socket socketClient= new Socket("localhost",5000);
    OutputStream os= socketClient.getOutputStream();
    out=new DataOutputStream(os);
    out.writeUTF(userInput);
    out.flush();
    socketClient.close();
}

Solution

  • You're using writeUTF on the client side, are you sure readLine on the server side is compatible with it? I had never seen that before, but the javadoc mentions it's a "modified" UTF-8 encoding. Try using readUTF instead, or simply use the regular write method.