简体   繁体   English

Java套接字编程写入readline

[英]Java socket programming writebytes to readline

I am trying to get a java server and client communicating. 我想让一个java服务器和客户端进行通信。 For streaming data to the server I have this code: 为了将数据流传输到服务器,我有以下代码:

  Socket ClientSocket = null;
ClientSocket = new Socket(IPAddress, portInt); 
DataOutputStream outToClient = new DataOutputStream(ClientSocket.getOutputStream());

    outToClient.writeBytes(command);
    outToClient.flush();

And for the server I have: 对于我有的服务器:

        ServerSocket mysocket = new ServerSocket(8081);
        Socket connectionsocket = mysocket.accept();

        BufferedReader inFromClient =
           new BufferedReader(new InputStreamReader(connectionsocket.getInputStream()));

        DataOutputStream outToClient = new DataOutputStream(connectionsocket.getOutputStream());

        //program hangs here, client not sending

        GetRequest = inFromClient.readLine();
        System.out.println("Received: " + GetRequest);

These are only short portions of the overall code, I have found that the program hangs on the server side when the readLine(); 这些只是整个代码的一小部分,我发现当readLine()时程序挂在服务器端; is reached. 到达了。 I am trying to send data with writeBytes(command); 我试图用writeBytes(命令)发送数据; where command is a string. 其中command是一个字符串。 Any suggestions? 有什么建议么? thanks. 谢谢。

writebytes to readline readbytes到readline

Stop right there. 停在那儿。 If you're using readLine() you're using BufferedReader , which is a Reader , which means you should be using a Writer to talk to it, which means you should be using a BufferedWriter , and as you're reading lines you must write lines, which means writing a line terminator (which you aren't presently doing), which means you should use BufferedWriter.newline() . 如果您正在使用readLine()那么您正在使用BufferedReader ,这是一个Reader ,这意味着您应该使用Writer与它通信,这意味着您应该使用BufferedWriter ,并且当您正在读取BufferedWriter ,您必须写行,这意味着写一个行终止符(你当前没有这样做),这意味着你应该使用BufferedWriter.newline()

Or PrintWriter.println(), but don't forget to check for errors, as it swallows exceptions. PrintWriter.println(),但不要忘记检查错误,因为它吞下异常。

Don't directly use readLine 不要直接使用readLine

Instead try this 而是试试这个

If( inFromClient.ready()){
   // read string here.
}

It might be possible that buffer is not ready and you are trying to read. 缓冲区可能没有准备就绪并且您正在尝试阅读。 So it can create problem. 所以它可以创造问题。

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

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