0
我在使用Java实现简单的多线程服务器时遇到问题。客户端 - 服务器多线程
我的想法是让服务器向所有客户端广播消息(不使用多播)。
为此,我正在实施一种广播方法。此方法将使用for循环,并循环遍历每个客户端线程,这些线程已存储在集合中。它会调用每个线程send(),它输出writeUTF()。
我的问题是针对2个客户A + B。
A输出:你好 B输出:您好
B就不会收到打招呼,而当再次B型,它将免费获赠的message.Code例如:
import java.net.*;
进口爪哇。 IO。 ; import java.util。;
公共类ServerThreadHandler继承Thread {
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){
}
}
Server代码:
// 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];
为什么你不给我们一个你迄今为止写的东西的例子,并告诉我们它在哪里崩溃。 –
当然,为了澄清我已经得到了服务器接受多个客户端,但现在的广播不是每个客户端,只有一个。例如上面的代码。 – Jnanathan
您尚未提供任何代码... –