0

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 :)

Tygo
  • 196
  • 3
  • 29

1 Answers1

1

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.

Boorsuk
  • 291
  • 1
  • 10
  • I basically have set this up already, but the idea with the map is great. If I want people to chat in rooms I could change the map to for example: map? and in the override of run send to all threads with the same channelname? – Tygo Sep 18 '20 at 14:33
  • Yea, sure but notice that map have only 2 parameters (Key,Value) so you cant add third one, if you wanna do this you need to create new Class with x,y,z Fields where at least one need to be a Socket so your map should looks like map where object is the class you create to store information about socket and channel name, Hope this help you :) – Boorsuk Sep 18 '20 at 14:39