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

发布于 2024-08-13 09:41:30 字数 2788 浏览 5 评论 0原文

我正在尝试为作业编写客户端和时间服务器,但无法让服务器接收来自客户端的第二个请求。第一个请求顺利完成。然后它就停滞了。事实上,我对这整件事很迷失,而且对 java 仍然很不舒服,所以我不知道我错过了什么。非常感谢任何指点。谢谢!

这是服务器代码:

 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));
      }

}

这是客户端:

 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());
           }
      }

 }

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. 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());
           }
      }

 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

左岸枫 2024-08-20 09:41:30

你需要另一个 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();
          }
      }
 }

You need to have another while loop, something like this,

  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();
          }
      }
 }
四叶草在未来唯美盛开 2024-08-20 09:41:30

来自 PrintWriter 文档

...如果启用自动刷新,则仅当调用 printlnprintfformat 方法之一时才会完成...

您的服务器正在调用 print() 并且从不刷新流,因此时间永远不会被发送。调用 println() 或显式刷新流。

另外,服务器在发送时间后立即关闭连接,因此客户端的第二个请求总是失败...

编辑:这里有一个有趣的怪癖 - 关闭 PrintWriter 应该刷新它(请参阅Writer),但由于操作的顺序,似乎发生的情况是:

  1. in. close() 关闭底层 Socket
  2. out.close() 刷新写入的数据,但不能(因为套接字现在已关闭)

不确定这到底是发生了什么,但是交换这两个语句的顺序会改变行为,大概给 out.close() 一个刷新的机会...

From the PrintWriter docs:

...if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked...

Your server is calling print() and never flushes the stream, so the time never gets sent. Either call println() or explicitly flush the stream.

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:

  1. in.close() closes the underlying Socket
  2. out.close() would flush the data written, but can't (as the socket is now closed)

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文