英文:
Java (Server)Socket multi room
问题
我正在尝试寻找一种创建多房间 Socket 的方法。这样用户就可以在不同的房间中与其他用户聊天,或者与其他用户私下聊天。是否有办法使用 java.net.Socket
和/或 java.net.ServerSocket
来实现这一点?
最佳方法是什么?我是否需要为每个房间和私人聊天都开启一个新端口?
我可以通过我的集成开发环境看到有一个 Socket getChannel()
方法,但是找不到有关此方法的任何信息。
也许我使用了错误的关键词。
我希望有人能帮助我解决这个问题
英文:
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
答案1
得分: 1
是的,有一种方法可以做到这一点。你需要为每个连接到服务器的用户创建一个新的线程,并将用户名和套接字存储在一个映射<username,socket>中,然后如果有人想要向特定用户发送消息,只需从映射中获取套接字并向该用户发送消息。
实现为所有用户创建线程的最简单方法如下:
ServerSocket serverSocket = new ServerSocket(6666);
while (true){
new User(serverSocket.accept()).start();
}
然后你只需要重写run()方法,监视用户是否向服务器发送任何消息,并将其传递给消息中指定的用户。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论