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
您尚未提供任何代碼... –