简体   繁体   English

Java服务器客户端| 服务器不会收到第二个请求

[英]Java server-client | server wont receive second request

I'm trying to write a client and time server for an assignment and I'm having trouble getting the server to receive the second request from the client. 我正在尝试编写用于分配的客户端和时间服务器,但无法使服务器接收来自客户端的第二个请求。 The first request goes through fine without a hitch. 第一个请求顺利进行。 then it just stalls. 然后就停了下来。 I'm actually pretty lost in this whole thing and rather uncomfortable with java still, so I have no idea what I'm missing. 实际上,我在整个过程中迷失了自己,并且仍然对java感到不舒服,所以我不知道我缺少了什么。 Any pointers are greatly appreciated. 任何指针,不胜感激。 Thanks! 谢谢!

Here's the sever code: 这是服务器代码:

 import java.io.*;
 import java.util.*;
 import java.net.*;
 import java.text.*;

 public class myServer {

      protected static final int PORT_NUMBER = 55555;

      public static void main( String args[]) {

      try {

           ServerSocket servsock = new ServerSocket(PORT_NUMBER);

           System.out.println("Server running...");

           while(true) {

                Socket sock = servsock.accept();

                System.out.println("Connection from: " + sock.getInetAddress());

                Scanner in = new Scanner(sock.getInputStream());
                PrintWriter out = new PrintWriter(sock.getOutputStream());
                String request = "";

                request = in.next();

                System.out.println("Request: " + request);

                if(request.toUpperCase().equals("TIME")) {
                     out.println(getTime());
                     out.flush();
                } else {
                     out.println("Invalid Request...");
                     out.flush();
                }

            }

        } catch(Exception e) {
           System.out.println(e.toString());
        }

    }

      protected static String getTime() {
           DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
           Date date = new Date();
           return (dateFormat.format(date));
      }

}

Here's the Client: 这是客户:

 import java.io.*;
 import java.util.*;
 import java.net.*;

 public class myClient {

        protected static final String HOST = "127.0.0.1";
        protected static final int PORT = 55555;

        protected static Socket sock;

        public static void main(String args[]) {

        try {

              sock = new Socket(HOST,PORT);

              System.out.println("Connected to " + HOST + " on port " + PORT);

              Scanner response = new Scanner(sock.getInputStream());
              PrintWriter request = new PrintWriter(sock.getOutputStream());
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              String txt = "";

              while(!txt.toUpperCase().equals("EXIT")) {

                    System.out.print("prompt:");
                    txt = in.readLine();

                    request.println(txt);
                    request.flush();

                    System.out.println(response.next());

              }

              request.close();
              response.close();
              in.close();
              sock.close();

           } catch(IOException e) {
              System.out.println(e.toString());
           }
      }

 }

You need to have another while loop, something like this, 您需要再进行一次while循环,如下所示:

  while(true) {                
      Socket sock = servsock.accept();                
      System.out.println("Connection from: " + sock.getInetAddress());                
      Scanner in = new Scanner(sock.getInputStream());                
      PrintWriter out = new PrintWriter(sock.getOutputStream());                
      String request = "";                
      while (in.hasNext()) {
          request = in.next();                
          System.out.println("Request: " + request);                
          if(request.toUpperCase().equals("TIME")) {                     
              out.println(getTime());
              out.flush();                
          } else {
               out.println("Invalid Request...");                     
               out.flush();
          }
      }
 }

From the PrintWriter docs : PrintWriter docs

...if automatic flushing is enabled it will be done only when one of the println , printf , or format methods is invoked... ...如果启用了自动刷新,则只有在调用printlnprintfformat方法之一时才执行...

Your server is calling print() and never flushes the stream, so the time never gets sent. 您的服务器正在调用print()并且从不刷新流,因此永远不会发送时间。 Either call println() or explicitly flush the stream. 调用println()或显式刷新流。

Also, the server closes the connection immediately after sending the time, so the client's second request always fails... 同样,服务器在发送时间后立即关闭连接,因此客户端的第二个请求始终失败...

Edit: there's an interesting quirk here - closing the PrintWriter ought to flush it (see the spec of Writer ), but due to the order of operations what seems to happen instead is: 编辑:这里有一个有趣的怪癖-关闭PrintWriter 应该刷新它(请参阅Writer的规范),但是由于操作的顺序, 似乎发生的是:

  1. in.close() closes the underlying Socket in.close()关闭基础Socket
  2. out.close() would flush the data written, but can't (as the socket is now closed) out.close() 刷新写入的数据,但不能(因为套接字现在已关闭)

Not sure this is exactly what's happening, but swapping the order of these two statements changes the behaviour, presumably giving out.close() a chance to flush... 不确定这是否正在发生,但是交换这两个语句的顺序会改变行为,大概给out.close()刷新的机会...

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

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