[英]How too allow a client on a server to send multiple messages? JAVA
我一直在建立一个聊天室,多个客户端可以在同一服务器上进行连接和交谈。 我唯一的问题是让每个客户端发送多个消息。 我一直在尝试使用不同的方法来循环执行此操作,但是我遇到了一些问题。 任何帮助将不胜感激:)谢谢。 这是代码:
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循环不断请求输入,但似乎没有用。
您是在READ.readLine()while循环之外制作的吗? 也许您永远不会结束输入字符,而那永远也不会终止。 另外,您将在while循环结束时关闭READ和WRITE,然后期望它们在下一次迭代时打开。 将这些和close语句移至与Socket相同的层。 这样,每次发送邮件时,客户端都希望服务器响应。 如果您不希望它们相互依赖,建议您在while(true)循环中将接收逻辑移至其自己的线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.