简体   繁体   English

服务器客户端通信Java

[英]server client communication java

I have this client, the server information is not important. 我有这个客户端,服务器信息并不重要。 The output of this code is very random. 此代码的输出是非常随机的。

class Client {
    public static void main(String args[]) throws Exception

    {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("127.0.0.1", 10004);//this will become the addr of the server you want to input.
        InetAddress host = clientSocket.getInetAddress();
        //      System.out.println(host);

        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        boolean exit = false;

        while (!exit) {
            while (inFromServer.ready()) {
                System.out.println(inFromServer.readLine());
            }
            String sentence = inFromUser.readLine();
            outToServer.writeBytes(sentence + "\n");
        }
        clientSocket.close();
    }
}

If I run this in debug mode, it has always the correct result. 如果我在调试模式下运行它,则始终具有正确的结果。 Eg 例如

  • please insert password 请输入密码
  • the user types pass 用户类型通过
  • pass correct 通过正确
  • please type command 请输入命令
  • and you type command 然后你输入命令
  • etc 等等
  • etc 等等

When it's not in debug mode, all goes wrong. 当它不在调试模式时,一切都会出错。 I don't even get the initial request from server. 我什至没有收到服务器的初始请求。 What is going on? 到底是怎么回事? I think the read line might be executed too fast? 我认为读取行可能执行得太快?

in.ready() does not wait for any data to be available. in.ready()不会等待任何数据可用。 It the server hasn't sent the data yet when you client reads that line, you're going to skip the readLine() completely. 如果服务器尚未发送数据,则当客户端读取该行时,您将完全跳过readLine()

Just remove that while and do a plain readLine() . 只是删除while ,做一个普通readLine()

If there are phases where you need to wait for multiple lines from the server, you'll need to implement more logic. 如果在某些阶段需要等待服务器发送多行,则需要实现更多逻辑。 Usually, the server will send an "end of message" marker to signify to the client that it is done. 通常,服务器将发送“消息结尾”标记,以向客户端表示已完成。 For example, when the server is done, it could send the message "END-OF-MESSAGE". 例如,服务器完成后,它可以发送消息“ END-OF-MESSAGE”。 In the client code, you would do: 在客户端代码中,您将执行以下操作:

boolean serverDone = false;
while (!serverDone) {
  String message = in.readLine();
  if (message == null) {
    // handle this problem: the server has closed the connection
    serverDone = true; // or return, or throw
  } else if ("END-OF-MESSAGE".equals(message)) {
    serverDone = true;
  }
}

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

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