How do I Send Data to All Threaded Clients in Java?

ぐ巨炮叔叔 提交于 2019-12-06 13:10:42

问题


I am fairly new to Java, and I am trying to construct a very basic Java Relay server that sends messages from clients to all connected clients. I have figured out how to do threading to allow multiple connections, but I am having trouble figuring out how to echo an incoming message to ALL connected socket threads.

Here is my Main.java source:

http://pastebin.com/vVewfv3s

Here is my SocketThread.java source:

http://pastebin.com/yHA2BcUi

Basically, I want to know the easiest way with my current coding setup to be able to send an incoming message from one client to all of the other clients. I am currently using the Windows telnet client as the client working with this server.


回答1:


One trivial way is to keep a collection of clients, say as a map or set. To send a message to all clients, you traverse the linked list of clients and put a reference to the message on each client's send queue. You need to protect these structures with proper inter-thread synchronization, of course.



来源:https://stackoverflow.com/questions/9969585/how-do-i-send-data-to-all-threaded-clients-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!