简体   繁体   中英

Java readline() keeping socket open

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!

I made effectively this same mistake when I was first doing sockets as well.

Don't use PrintWriter with BufferedReader . They're incompatible. By comments, 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.

方法readLine()预期行字符“ \\ n”的结尾可能是您的问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM