问答详情
源自:-

TCP多线程通信

怎样实现服务器把各客户机发来的信息读出来再分发给其它客户端?服务器的读出来的信息要进行如何处理才能发送给客户端,是的客户端正确读取?

提问者:慕粉2213397909 2016-12-07 23:12

个回答

  • gabbi520
    2018-05-02 13:53:37
    已采纳

    //新建一个类。将类单例化。类中生命一个Vector<socket>  再添加

    public class ChatManager {


    private ChatManager(){}

    private static final ChatManager cm = new ChatManager();

    public static ChatManager getChatManager() {

    return cm;

    }

    Vector<Socket> vector = new Vector<Socket>();

    public void add(Socket s) {

    vector.add(s);

    }

    public void remove(Socket cs) {

    vector.remove(s);

    }

    public void publish(Socket s,String out) {

    for (int i = 0; i < vector.size(); i++) {

    Socket ChatSocket = vector.get(i);

    if (!s.equals(ChatSocket)) {

        ChatSocket.getOutputStream().write((out+"\n").getBytes("UTF-8"));

    }

    }

    }

    }