简体   繁体   中英

Java (Server)Socket multi room

I am trying to find a way to create a multiroom Socket. So users can chat in different rooms or privately with other users. Is there a way to do this with the java.net.Socket and/or java.net.ServerSocket ?

What is the best way to do this? Do I need to open a new port for each room and private chat?

I can see through my IDE that there is a Socket getChannel() , but unable to find anything about this. Perhaps I am looking with the wrong words.

I hope someone can help me with this :)

Yea, there's a way to do it. You need to create a new Thread for every user that connect to your server and store the username and socket in a map<username,socket> then if someone wan't to send a message to specific user, you just pick up socket from a map and send a message to this user.

Simplest way to achieve a thread for all users looks like

ServerSocket serverSocket = new ServerSocket(6666);
        while (true){
            new User(serverSocket.accept()).start();
        }

Then you just need to ovveride run() method to monitor if user send any message to our server and pass it to a user witch is specified in message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM