聊天服务器:所有线程如何发送传入消息

时间:2014-02-20 19:01:58

标签: java multithreading sockets

我正在开发聊天服务器和客户端。每个客户端连接都放在一个threadPool中。当有人发送消息时,服务器应该接收消息并将其发送给所有人(包括发件人)。我在考虑所有线程都可以在其中编写的常见ArrayList,但我不确定这是否是最好的主意。您能否帮助实现这一目标,并告诉我如何将传入的消息发送给所有人。到目前为止,这是我的代码:

class:ChessHeroCharSrv.java

public class ChessHeroChatSrv {

    static final int PORT = 333;
    static ServerSocket socket;
    static Vector<ClientHandler> threadPool = new Vector<ClientHandler>();

    public static void main(String[] args) {

    try {
        socket = new ServerSocket(PORT);
        System.out.println("Server is started!");

        while (true) {
            Socket incoming = socket.accept();
            incoming.setKeepAlive(true);
            new ClientHandler(incoming, threadPool).start();
            System.out.println("New client connected!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class:ClientHandler.java

public class ClientHandler extends Thread {

protected Socket socket;
protected Vector threadPool;
protected SimpleDateFormat simpleDataFormat;

public ClientHandler(Socket socket, Vector threadPool) {

    this.socket = socket;
    this.threadPool = threadPool;
    threadPool.add(this);
}

public void sendMessage(String outboundMessage) {

}

public void run() {

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));

            PrintWriter out = new PrintWriter(new OutputStreamWriter(
                socket.getOutputStream()));

            // out.println("Hello!\n Enter 'quit' to exit.");
            // out.flush();

            while (true) {
                String inboundMessage = in.readLine();

                if (inboundMessage == null) {
                    break;
                } else {
                        System.out.println(inboundMessage);

                // Send the message to everyone

                // outboundMessage = "<" + simpleDataFormat.format(new
                // Date()) + ">";

                // out.println(outboundMessage);
                // out.flush();
                        }
            }
            socket.close();

        } catch (IOException e) {
            System.out.println("Client disconnected!");
        } finally {
            threadPool.remove(this);
        }
    }
}

0 个答案:

没有答案