如何将数据发送到Java中的所有线程客户端? [英] How do I Send Data to All Threaded Clients in Java?
问题描述
我对Java还是很陌生,我正在尝试构建一个非常基本的Java Relay服务器,该服务器将消息从客户端发送到所有连接的客户端.我已经弄清楚如何做线程处理以允许多个连接,但是我很难弄清楚如何将传入的消息回显到所有连接的套接字线程.
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.
这是我的Main.java来源:
Here is my Main.java source:
这是我的SocketThread.java来源:
Here is my SocketThread.java source:
基本上,我想了解当前编码设置的最简单方法,即能够将传入消息从一个客户端发送到所有其他客户端.我目前正在使用Windows telnet客户端作为与此服务器一起使用的客户端.
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.
推荐答案
一种简单的方法是保留一组客户,例如以地图或集合的形式.要将消息发送给所有客户端,请遍历客户端的链接列表,并在每个客户端的发送队列上放置对该消息的引用.当然,您需要通过适当的线程间同步来保护这些结构.
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.
这篇关于如何将数据发送到Java中的所有线程客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!