【发布时间】: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