如何允许服务器上的客户端发送多条消息? JAVA

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,然后期望它们在下一次迭代中打开。将这些和关闭语句移动到与套接字相同的层。 这样一来,每次您发送内​​容时,您的客户端都会期待服务器的响应。如果你不希望它们相互依赖,我建议在 while(true) 循环中将接收逻辑移动到它自己的线程。