【发布时间】:2011-11-21 18:17:57
【问题描述】:
我在用 Java 实现简单的多线程服务器时遇到问题。
我的想法是让服务器向所有客户端广播消息(不使用多播)。
为此,我正在实施广播方法。此方法将使用一个 for 循环,并循环遍历我存储在集合中的每个客户端线程。它会调用每个线程send(),输出writeUTF()。
我的问题是针对 2 个客户 A+B。
A 输出:你好 B 输出:你好
B不会收到你好,当B再次输入时,它会收到A的消息。代码示例:
import java.net.*;
导入 java.io.; 导入 java.util.;
公共类 ServerThreadHandler 扩展线程 {
private AuctionServer server = null;
private Socket socket = null;
private String name = null;
private int ID = -1;
private DataInputStream dataIn = null;
public DataOutputStream dataOut = null;
private Thread thread;
protected static Vector handlers = new Vector();
// reason server is used here is because ian was calling a server method broadcast
// from inside the
public ServerThreadHandler(AuctionServer server, Socket socket, String name) throws IOException{
this.server = server;
this.socket = socket;
this.name = name;
dataIn = new DataInputStream( new
BufferedInputStream(socket.getInputStream()));
dataOut = new DataOutputStream(socket.getOutputStream());
}
// handles a specific client.
public void run(){
System.out.println("Server running..");
while(true){
try{
// broadcast to all clients. This will only be one client in this case.
server.broadcast(dataIn.readUTF());
int pause = (int)(Math.random() * 3000);
Thread.sleep(pause);
}
catch(IOException e){
System.out.println(e.getMessage());
}
catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
}
public void send(String msg){
try{
dataOut.writeUTF(msg);
dataOut.flush();
}
catch(IOException e){
}
}
服务器代码:
// broadcast this to clients.
public void broadcast(String msg){
for(int i = 0; i < clientCount; i++){
clients[i].send(msg);
}
}
客户[]在哪里
private ServerThreadHandler clients[] = new ServerThreadHandler[3];
【问题讨论】:
-
你为什么不给我们一个你到目前为止写的例子,并告诉我们它在哪里崩溃。
-
当然,澄清一下我已经让服务器接受多个客户端,但现在广播不是对每个客户端,只对一个客户端。示例在上面的代码中。
-
你还没有提供任何代码...
-
好的,我尝试编辑帖子以提供代码,但每次都出现错误。如果你愿意,我会继续努力。我也更新了问题问题。
-
您正在另一个线程 (???) 的运行中创建一个线程,但从未启动它。这非常令人困惑......
标签: java multithreading client