Java 保存套接字连接

Java 保存套接字连接,java,sockets,Java,Sockets,所以我准备创建一个类似IRC的聊天程序。 完成了客户端应用程序的所有GUI工作 现在我的问题是,我想让多个用户连接到一台服务器。该服务器有很多聊天室,每个聊天室都有一个当前用户列表 如何创建Methode User.message(字符串消息)。我把插座放在哪里?我可以只在我的用户类中存储一个ClientConnection,它是一个可运行的吗 public class ClientConnection implements Runnable { private final Socket

所以我准备创建一个类似IRC的聊天程序。 完成了客户端应用程序的所有GUI工作

现在我的问题是,我想让多个用户连接到一台服务器。该服务器有很多聊天室,每个聊天室都有一个当前用户列表

如何创建Methode User.message(字符串消息)。我把插座放在哪里?我可以只在我的用户类中存储一个ClientConnection,它是一个可运行的吗

public class ClientConnection implements Runnable {
    private final Socket CLIENT;
    private String sendLine;
    private String nextLine;

    private BufferedReader in;
    private PrintWriter out;
    public ClientConnection(Socket s){
        CLIENT = s;

        try{
            in = new BufferedReader(new InputStreamReader(CLIENT.getInputStream()));
            out = new PrintWriter(CLIENT.getOutputStream(), false);
        }catch(IOException IOEx){
            IOEx.printStackTrace();
        }

        sendLine = "DATE";
    }

    public void run(){
        try{

            while(true){

                if((nextLine = in.readLine()) != null){
                    System.out.println(nextLine);
                }

                if(sendLine != null){
                    out.println(sendLine);
                    sendLine = null;
                }
            }

        }catch(SocketException SOEx){
                System.out.println("Client Connection Closed");
                return;
        }catch(IOException IOEx){
            IOEx.printStackTrace();
        }

    }

    public void sendMessage(String m){
        this.sendLine = m;
    }

您必须使用中介来存储所有活动用户(
ClientConnection
-s)。此messenger用于向消费者发送组消息。
使用
ClientConnection
中的构造函数在中介中注册它。

“必须使用中介”-我没有意识到这是聊天引擎唯一可能的实现???这太好了,谢谢,我真的不知道搜索什么。你的阅读循环没有意义。如果
readLine()
返回null,则必须停止读取,并可能关闭套接字。