一台服务器多个客户端 [英] one server multiple clients
问题描述
我遇到以下问题:
- 我需要编写一个服务器程序,将接受多个客户端
- 所有客户都从服务器订阅相同的数据,例如股价更新.
- 每个客户端都可以向服务器发送简单的命令,例如登录",停止"
这是我的解决方案,由于我对多线程/tcp的经验不是很丰富,所以我想知道这是一个好的解决方案吗?如果没有,是否有更好的解决方案?每个客户端套接字是否都必须有一个线程?谢谢 顺便说一句:对每个人都感到困惑,这是一个很小的项目,只涉及5-10个班级.
So here is my solution, Since I am not very experianced in multithread/tcp, I want to know is it a good solution? if not, is there any better solution? is it necessary to have a thread for each client socket? Thanks BTW: sorry for confusing every one, it is a small project that only involve 5-10 classes.
class AcceptThread {
......
public void run () {
ControlThread controlThread = new ControlThread();
controlThread.start();
Socket socket = new Socket(port);
while (!stop) {
Socket s = socket.accept();
controlThread.addClient (s);
}
}
}
class ControlThread {
Set<Scoket> clients;
SendDataThread sendDataThread;
public ControlThread () {
sendDataThread = new SendDataThread();
sendDataThread.start();
}
public void addClient (Socket socket) {
clients.add(socket);
sendDataThread.addListener(socket);
}
public void run () {
......
for (Socket s : clients) {
if (s.getInputStream().available()) {
//read command from s
}
}
......
}
}
class SendDataThread () {
Set<Scoket> listeners;
public void addListener (Socket s) {
listeners.add(s);
}
public void run () {
for (Socket s: listeners) {
// send data to each listener
}
}
}
推荐答案
每个客户端套接字是否需要一个线程?
不,事实上,我什至不推荐它.如果这是一个小项目,并且您不想使用任何现有的库,建议您使用 SelectableChannels
.使用所谓的选择器,您可以轻松地以非阻塞方式监视客户端的传入数据.
No, as a matter of fact, I wouldn't even not recommend it. If it's a small project and you don't want to use any existing library, I would suggest you use the java.nio
package and the SelectableChannels
. With a so called selector you can easily monitor clients for incoming data in a non-blocking way.
以下是一些有用的链接:
Here are a few useful links:
- NIO Examples (from the official tutorial)
- The Rox Java NIO Tutorial
这篇关于一台服务器多个客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!