各位。我是网络编程的新手,遇到了以下问题。我需要编写一种可以同时与多个客户端保持连接的服务器。我写的内容如下:
主
类:
public class Main {
public static void main(String args[]) throws Exception{
ConnectionUtils.waitForClients();
}
}
ConnectionUtils
类:
public class ConnectionUtils {
private static ServerSocket server;
static{
try {
server = new ServerSocket(54321);
} catch (Exception e) {
}
}
private static Runnable acceptor = new Runnable() {
@Override
public void run() {
try {
Client c = new Client(server.accept());
new Thread(acceptor).start();
c.sendLine("Hello client \n");
} catch (Exception e) {
}
}
};
public static void waitForClients(){
Thread clientAcceptor = new Thread(acceptor);
clientAcceptor.start();
}
}
它或多或少是有效的。但这种方法的缺点是什么?我怀疑他们有太多缺点,但我无法捕捉到他们。
最佳答案
问题在于您创建了无限数量的线程
,其中线程
是昂贵的资源。您应该使用 ThreadPool 来限制程序中创建的线程数量。
考虑使用 Executors
而不是使用此低级代码 In Oracle documentation about Executors, there is an example similar to what you doing. Check it out!
关于java - 与多个客户端的 ServerSocket 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26947559/