【发布时间】:2020-07-24 14:09:33
【问题描述】:
我有一个客户端-服务器聊天程序,服务器将为每个接受的连接创建一个新线程,其中 NewClient 扩展 Thread 以处理来自特定客户端的请求。
这是服务器代码的sn-p:
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的run方法如下:
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);
}
}
}
我知道如果这是一个匿名线程,我可以从服务器内部调用广播方法。如何在线程类中调用此方法?
非常感谢您的反馈。
【问题讨论】:
-
将服务器的引用传递给它的构造函数?
-
你的意思是newClient(socket, clientCount, this)吗?
-
是的,类似的。
-
谢谢,我一开始都没有考虑过。
标签: java multithreading server client client-server