Как клиентская сторона узнает, когда сервер ожидает данные в Java? - PullRequest
0 голосов
/ 09 января 2019

Это мой код клиента:

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 голосов
/ 09 января 2019

Как кто-то предложил в комментариях, вы должны определить протокол для вашего конкретного взаимодействия клиент-сервер, это означает, что клиент должен знать, какими будут все возможные ответы от сервера, и обрабатывать их единым образом, как вы решите, и одинаково для всех возможных звонков с клиента на сервер. Вы должны проверить этот пост для дальнейшего вдохновения.

Я не могу помочь вам определить протокол, который зависит от вас и вашей бизнес-логики и выходит за рамки данной платформы, но я могу сказать, что вам нужно сделать несколько настроек, чтобы иметь возможность прослушивать сообщения от клиентов на сервер.

Настройка кода клиента:

    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());
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...