我在解决我的Uni项目时遇到了问题。它是关于客户端/服务器通信的,而练习是创建一个EchoServer重复每个客户端的消息并将其直接发送回客户端。当客户端仅发送空消息时,服务器关闭。到目前为止,我的代码看起来不错,但我的问题是,出于测试目的,我希望打印出服务器/客户端之间的对话。但我只能看到对话的一瞥,然后它似乎被覆盖了#34;通过"协议开始"消息从一开始。这是我的代码:
服务器
public class EchoServer {
public static void main(String [] args) {
try {
ServerSocket server = new ServerSocket(Integer.parseInt(args[0]));
System.out.print("Server läuft");
Socket s;
while(true) {
s = server.accept();
new EchoProtokoll(s).startProtocol();}
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
协定
public class EchoProtokoll {
Socket s;
BufferedReader vomClient;
PrintWriter zumClient;
public EchoProtokoll(Socket s) {
this.s = s;
try {
zumClient = new PrintWriter(s.getOutputStream(),false);
//I also tried true as parameter
vomClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void startProtocol() {
System.out.print("Protokoll gestartet");
try {
String client;
while((client=vomClient.readLine()).length()>0) {
System.out.print("Client schreibt:"+vomClient.readLine());
zumClient.println("Echo: "+client);
}
System.out.print("Protokoll beendet");
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
public class EchoClient2 extends Thread {
Socket echoSocket;
PrintWriter out;
BufferedReader in;
int port;
public EchoClient2(int port) {
this.port = port;
}
public void run() {
try {
echoSocket = new Socket("localhost",port);
out = new PrintWriter(echoSocket.getOutputStream(),false);
String nachricht;
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
while((nachricht=Aufgabe1.getStr(2)).length()>0) {
out.println(nachricht);
System.out.println("Hallo vom Server:"+in.readLine());
}
String s="";
out.println(s);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
(方法" getStr(int t)"在另一个由uni给出的类中,基本上随机生成一段时间的字符串。但我怀疑它有什么问题。在该类中,生成5个客户端用于并行访问服务器。如果需要,我也可以在此发布此类,但我非常怀疑问题在于Uni的代码。)
编辑:端口是1025