如何将数据发送到Java中的所有线程客户端? [英] How do I Send Data to All Threaded Clients in Java?

查看:184
本文介绍了如何将数据发送到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:

http://pastebin.com/vVewfv3s

这是我的SocketThread.java来源:

Here is my SocketThread.java source:

http://pastebin.com/yHA2BcUi

基本上,我想了解当前编码设置的最简单方法,即能够将传入消息从一个客户端发送到所有其他客户端.我目前正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆