我有一个客户端-服务器聊天程序,其中服务器将为每个接受的连接创建一个新线程,其中NewClient扩展线程以处理来自特定客户端的请求。
这是服务器代码的片段:
public void startServer() {
// thread to handle requests
new Thread(() -> {
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started at " + new Date());
while (true) {
// listen for connection request
Socket socket = serverSocket.accept();
// increment total clients connected
clientCount++;
// create new client
NewClient newClient = new NewClient(socket, clientCount);
// add client to active client list
activeClientList.add(newClient);
// start thread
newClient.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
在NewClient中,线程将循环并检查输入流。如果检测到输入流,我希望它向所有客户端广播输入流中的消息。
这里是NewClient的运行方法:
public void run() {
while(true) {
try {
// read from client
Data message = (Data) objectInputStream.readObject();
System.out.println("Received " + message.text + " from " + message.name);
// broadcast to all clients
// broadcastMessage(message)
} catch (IOException | ClassNotFoundException e) {
System.out.println("Failed to get input stream");
e.printStackTrace();
}
}
}
在服务器类的后面,有一个称为broadcastMessage(Data data)的方法,它将遍历数组列表中所有已连接的客户端,并使用输出流将数据发送到每个客户端。
这里是方法:
public synchronized void broadcastMessage(Data data) {
Integer size = activeClientList.size();
// loop through all clients
for(int i=size-1;i>=0;i--) {
NewClient client = activeClientList.get(i);
if(!client.writeToClient(data)) {
activeClientList.remove(i);
// notify users of disconnect
Data update = new Data(data.name, data.name + " has disconnected.");
broadcastMessage(update);
}
}
}
我知道,如果这是一个匿名线程,我可以从服务器内部调用广播方法。如何在线程类中调用此方法?
非常感谢您的反馈。
// create new client
NewClient newClient = new NewClient(socket, clientCount, this);
感谢约翰内斯·库恩(Johannes Kuhn)指出可以将服务器传递到线程构造函数中以调用该方法。