java - Java中客户端如何知道服务器何时等待数据?

标签 java sockets server client

这是我的客户端代码:

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 循环中执行此操作吗?

最佳答案

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

我无法帮助您定义一个协议(protocol),因为这取决于您和您的业务逻辑,并且超出了该平台的范围,但我可以说您需要进行一些调整才能监听来自客户端的消息服务器。

客户端代码调整:

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

关于java - Java中客户端如何知道服务器何时等待数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102267/

相关文章:

java - Swing 按钮使标签或文本字段发生变化

java - 动画师集 : Circular dependencies cannot exist

java - 无法在开放类次环境中启动 hazelcast。服务器套接字绑定(bind)失败。没有权限

ios - XMPP 与服务器连接并在 iOS 中配置客户端

sql-server - powershell 从表中提取值

java - 嵌入式 tomcat 7 servlet 3.0 注释不起作用

java - 技术栈建议 : Google App Engine, FLEX、GraniteDS (Tide)、Java、Spring

Python Opencv 和 Sockets - 以 h264 编码的流视频

java - Java 到 Objective-C 的 Socket 连接

ruby-on-rails - puma 启动导致 "There is already a server bound to: <socket>"错误