保存套接字连接

时间:2015-05-25 12:24:51

标签: java sockets

所以我即将创建一个像Chat Proramm这样的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;
    }

1 个答案:

答案 0 :(得分:0)

您必须使用中介来存储所有活动用户(ClientConnection -s)。此信使用于向消费者发送群组消息。 使用ClientConnection中的构造函数将其注册到调解器中。