Как кто-то предложил в комментариях, вы должны определить протокол для вашего конкретного взаимодействия клиент-сервер, это означает, что клиент должен знать, какими будут все возможные ответы от сервера, и обрабатывать их единым образом, как вы решите, и одинаково для всех возможных звонков с клиента на сервер. Вы должны проверить этот пост для дальнейшего вдохновения.
Я не могу помочь вам определить протокол, который зависит от вас и вашей бизнес-логики и выходит за рамки данной платформы, но я могу сказать, что вам нужно сделать несколько настроек, чтобы иметь возможность прослушивать сообщения от клиентов на сервер.
Настройка кода клиента:
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());
}
}