-1
所以我想在Java中設置一個非常基本的聊天應用程序。所以我寫了一個服務器和一個客戶端。Java ServerSocket/Server只能運行一次
服務器:
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循環,這樣我可以重複發送消息。但由於某種原因它只能使用一次。你輸入一段文字,然後服務器返回它。你可以輸入另一個,但服務器不會返回它。
有人知道爲什麼嗎?
您的代碼的整體結構不清楚(哪個類包含哪個方法或成員,哪些線程正在運行)。請粘貼一個最小的,完整的,可驗證的例子。 – Heri