【问题标题】:How does the client side know when the server waits for data in Java?客户端如何知道服务器何时等待 Java 中的数据?
【发布时间】:2019-01-09 01:53:11
【问题描述】:

这是我的客户端代码:

public static void main (String args[]) {
    Socket socket  = null;
    Scanner scanner = new Scanner(System.in);
    try{
        int serverPort = Integer.parseInt(args[1]);
        socket = new Socket(args[0], serverPort);    
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        while(true){
            String temp=in.readLine();
            if (temp==null){
                break;
            }
            System.out.println(temp);
        }
    }catch (UnknownHostException e)  {System.out.println("Socket:"+e.getMessage());}    
     catch (EOFException e){System.out.println("EOF:"+e.getMessage());}
     catch (IOException e){System.out.println("readline:"+e.getMessage());}
     finally {if(socket!=null) try {socket.close();}catch (IOException e){System.out.println("close:"+e.getMessage());}}
 }

这是我的服务器代码的一部分:

public static void main(String[] args) throws Exception{
    try{
        int serverPort = 7896; // the server port
        ServerSocket listenSocket = new ServerSocket(serverPort);
        while(true) {
            Socket clientSocket = listenSocket.accept();
            System.out.println("Request from client" + clientSocket.getInetAddress()+"at port "+ clientSocket.getPort());               
            Connection c = new Connection(clientSocket);
        }
     } catch(IOException e) {System.out.println("Listen socket:"+e.getMessage());}
}

private static class Connection extends Thread{
    private Socket socket;

    public Connection(Socket socket) {
        this.socket = socket;
        System.out.println("New client connected at " + socket);
        this.start();
    }

    @Override
    public void run() {
           try {
               BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
               begin(in,out);  
           }catch (IOException e) {
                System.out.println("Error handling client");
           }finally{
                 try { socket.close(); } catch (IOException e) {}
                 System.out.println("Connection with client closed");
           }
    }

}

public static void begin(BufferedReader in, PrintWriter out){
    String userChoice=null;

    out.println("----------");
    out.println("MailServer:");
    out.println("----------");
    out.println("Hello, you connected as a guest.");
    printMenu(out); //a menu with some choices

    out.println("Please type your choice: ");
    try{
        userChoice=in.readLine();
    }
    catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

在客户端,我在 while 循环中显示来自服务器的所有消息。事情是在一些消息之后服务器等待来自客户端的消息。之后,服务器发送更多消息并再次等待来自客户端的消息。我怎么知道有时服务器会停止发送消息并等待答复?为此,我将使用客户端的 out 变量。我会在那个 while 循环中这样做吗?

【问题讨论】:

  • 您需要设计一个协议。这就是客户端和服务器通信的方式。没有一个,你只会在黑暗中挣扎。
  • 具体是在问,客户端怎么知道服务器在等待呢?如果是这样,@ElliottFrisch 的建议是正确的。如果您提供更清晰的说明,我可以帮助您解决问题
  • 是的。我正在尝试创建一个邮件服务器。该菜单为客户提供了一些选项(登录、注册等)。在客户端发送他的消息(登录、注册等)后,其他消息将从服务器发送到客户端(带有发送电子邮件、阅读电子邮件等的菜单),服务器将再次等待消息(从新的选择菜单,例如阅读电子邮件)等等..
  • @SavvasTh 我发布的答案是否有帮助,请尊重您需要更多时间来帮助您提出非常模糊和格式错误的问题。
  • 嘿抱歉回复晚了,我检查了你的答案,但我用另一种类似的方式解决了它。每次服务器需要回复时,我都会在“waiting_for_reply”之前发送一条消息,并且在客户端应用程序中,我会检查每条消息,如果消息等于该消息,则表示服务器正在等待回复。不是解决它的最佳方法,但是!不过感谢您的帮助!

标签: java sockets server client


【解决方案1】:

正如 cmets 中有人建议的那样,您必须为特定的客户端-服务器交互定义一个协议,这意味着客户端必须知道来自服务器的所有可能响应是什么,并以您决定的统一方式处理这些响应从客户端到服务器的所有可能调用都相同。您应该查看this post 以获得更多灵感。

我无法帮助您定义协议,因为这取决于您和您的业务逻辑并且超出了该平台的范围,但我可以说您需要进行一些调整才能在服务器。

客户端代码调整:

    public static void main (String args[]) {
    Socket socket  = null;
    Scanner scanner = new Scanner(System.in);
    try{
        int serverPort = Integer.parseInt(args[1]);
        socket = new Socket(args[0], serverPort);    
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        while(true){
            String temp=in.readLine();
            if (temp==null){
                break;
            }

            String x = "empty" // name this some default option so you can handle it in the server and know that it was never set
            if (temp == "Hello, you connected as a guest.") {
                // process the help menu items here and make a decision on what to send
                // ex) you chose option 'A', save it in a variable, lets say String x = "A"
            } else if (temp == ) {
                // now that the server asks for your response, you know that it is waiting... send the response
                // out.println(x) 
            }
            System.out.println(temp);
        }
    }catch (UnknownHostException e)  {System.out.println("Socket:"+e.getMessage());}    
     catch (EOFException e){System.out.println("EOF:"+e.getMessage());}
     catch (IOException e){System.out.println("readline:"+e.getMessage());}
     finally {if(socket!=null) try {socket.close();}catch (IOException e){System.out.println("close:"+e.getMessage());}}
}

服务器代码调整:

private static class Connection extends Thread {
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public Connection(Socket socket, BufferedReader input, PrintWriter output) {
        this.socket = socket;
        this.in = in
        this.out = output
        System.out.println("New client connected at " + socket);
        this.start();
    }
    @Override
    public void run() {
        while(true) {
            begin()
        }
    }

    public static void begin(){
        String userChoice = null;

        out.println("----------");
        out.println("MailServer:");
        out.println("----------");
        out.println("Hello, you connected as a guest.");
        printMenu(out); //a menu with some choices

        this.out.println("Please type your choice: ");
        try{
            userChoice = this.in.readLine();
            // handle user choices here
                if (userChoice == "A") {
                // do whatever you need for option A
            }
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

public static void main(String[] args) throws Exception{
    try{
        int serverPort = 7896; // the server port
        ServerSocket listenSocket = new ServerSocket(serverPort);
        while(true) {
            Socket clientSocket = listenSocket.accept();
            System.out.println("Request from client" + clientSocket.getInetAddress()+"at port "+ clientSocket.getPort());

            try {
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter socketOutput = new PrintWriter(socket.getOutputStream(), true);               
                Connection c = new Connection(clientSocket, socketInput, socketOutput);
            } catch (IOException e) {
                System.out.println("Error handling client");
            } finally{
                try { socket.close(); } catch (IOException e) {}
                System.out.println("Connection with client closed");
            }
        }
    } catch(IOException e) {
        System.out.println("Listen socket:"+e.getMessage());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 2012-11-10
    相关资源
    最近更新 更多