所以我想用Java设置一个非常基本的聊天应用程序。所以我写了一个服务器和一个客户端。
服务器:
port = 9694;
server = new ServerSocket(port);
client = server.accept();
optStream = client.getOutputStream();
optWriter = new PrintWriter(optStream);
iptStream = client.getInputStream();
iptReader = new BufferedReader(new InputStreamReader(iptStream));
while(terminateServer == false){
String s = null;
if((s = iptReader.readLine()) != null){
optWriter.write(s + "\n");
optWriter.flush();
}
}
optWriter.close();
iptReader.close();
客户端:
client = new Socket("192.168.0.100", 9694);
sc = new Scanner(System.in);
optStream = client.getOutputStream();
optWriter = new PrintWriter(optStream);
iptStream = client.getInputStream();
iptReader = new BufferedReader(new InputStreamReader(iptStream));
while(terminateClient == false){
this.send(getMessage());
this.receive();
}
optWriter.close();
iptReader.close();
}
public void send(String text){
String s = null;
s = text;
optWriter.write(s + "\n");
optWriter.flush();
}
public void receive(){
String a = null;
try {
while((a=iptReader.readLine()) != null){
System.out.println(a);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getMessage(){
String s = null;
s = sc.nextLine();
return s;
}
我的计划是使用while循环,以便我可以重复发送消息。但由于某种原因它只能工作一次。您键入一段文本然后服务器返回它。您可以键入另一个,但服务器不会返回它。
有人知道为什么?
答案 0 :(得分:0)
readLine()
在流末尾返回null,在这种情况下,仅在对等方断开连接时才会发生。因此while
调用周围的receive()
循环完全没有意义。一旦对等体断开连接,无论您多少次呼叫,readLine()
都将返回假。