У меня проблема с реализацией простого многопоточного сервера на Java.
Моя идея заключается в том, чтобы сервер передавал сообщения всем клиентам (без использования многоадресной рассылки).
Для этого я реализую метод вещания. Этот метод будет использовать цикл for и проходить по каждому клиентскому потоку, который я сохранил в коллекции. Он будет вызывать каждый поток send (), который выводит writeUTF ().
Моя проблема для 2 клиентов A + B.
А выходы: привет
B выводит: привет там
B не получит привет, и когда B наберет снова, будет получено сообщение A. Пример кода:
import java.net.*;
import java.io. ;
import 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];