简体   繁体   English

Java readline()保持套接字打开

[英]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 . 不要将PrintWriterBufferedReader一起使用。 They're incompatible. 它们是不兼容的。 By comments, PrintWriter actually hides critical exceptions, so they shouldn't be used in networking. 通过评论, PrintWriter实际上隐藏了关键异常,因此不应在网络中使用它们。 Instead, use a DataInputStream and DataOutputStream for communications. 而是使用DataInputStreamDataOutputStream进行通信。

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: 然后,使用writeUTFreadUTF发送和接收,如下所示:

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; 原因与UTF编码有关; a BufferedReader expects a certain string encoding, which PrintWriter does not give. BufferedReader需要某种字符串编码,而PrintWriter则不提供。 Thus, the read/write hangs. 因此,读/写挂起。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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