Reputation: 618
I am trying to have my client connect to my server, and depending on the command send some string back to the client. Currently the app connects and can send strings to the server very nicely. However when I send the command which instructs the server to send something back it hangs. I found that the problem occurs when the client attempts to read the line send from the server.
Server
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.println("GETDATA" + "\n");
out.flush();
out.close();
Client
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
incomingLine = fromServer.readLine();
Log.d("HERE", "NOT " + incomingLine);
fromServer.close();
Thanks!
Upvotes: 0
Views: 811
Reputation: 1
The method readLine() expects an end of line character "\n" maybe that's your problem
Upvotes: 0
Reputation:
I made effectively this same mistake when I was first doing sockets as well.
Don't use By comments, PrintWriter
with BufferedReader
. They're incompatible.PrintWriter
actually hides critical exceptions, so they shouldn't be used in networking. Instead, use a DataInputStream
and DataOutputStream
for communications.
client = new Socket(hostname, port);
inStr = new DataInputStream(client.getInputStream());
outStr = new DataOutputStream(client.getOutputStream());
Then, send and receive using writeUTF
and readUTF
, like so:
public void send(String data) throws IOException {
outStr.writeUTF(data); outStr.flush();
}
public String recv() throws IOException {return inStr.readUTF();}
The reason has to do with the UTF encoding; a BufferedReader
expects a certain string encoding, which PrintWriter
does not give. Thus, the read/write hangs.
Upvotes: 1