【发布时间】:2018-08-16 02:34:14
【问题描述】:
我一直在创建一个聊天室,多个客户端可以在同一台服务器上连接并一起交谈。 我遇到的唯一问题是让每个客户端发送多条消息。我一直在尝试不同的方法来循环该方法,但我遇到了一些问题。 任何帮助将不胜感激:) 谢谢。 代码如下:
public class Client {
public static void main(String[] args){
Scanner clientInput = new Scanner(System.in);
try {
Socket SOCK = new Socket("localhost", 14001);
System.out.println("Client started!");
//Streams
while(true){
OutputStream OUT = SOCK.getOutputStream(); //writing data to a destination
PrintWriter WRITE = new PrintWriter(OUT); // PrintWriter prints formatted representations of objects to a text-output stream
InputStream in = SOCK.getInputStream(); //reads data from a source
BufferedReader READ = new BufferedReader(new InputStreamReader(in));
//---------------------------------
System.out.print("My input: ");
String atServer = clientInput.nextLine();
WRITE.write(atServer + "\n");
WRITE.flush(); //flushes the stream
String stream = null;
while((stream = READ.readLine()) != null){ //if stream is not empty
System.out.println("Client said: " + stream);
}
READ.close();
WRITE.close();
}
} catch (UnknownHostException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
我尝试使用 while 循环来不断地请求输入,但似乎不起作用。
【问题讨论】:
标签: java loops server client chat