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

时间:2019-01-09 01:53:11

标签: 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循环内这样做吗?

1 个答案:

答案 0 :(得分:1)

正如评论中所建议的那样,您必须为特定的客户端-服务器交互定义协议,这意味着客户端必须知道来自服务器的所有可能响应,并以统一的方式处理您决定和决定的响应。对于从客户端到服务器的所有可能的调用,此操作均相同。您应该签出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());
    }
}