民间。我是网络编程的新手,遇到了以下问题。我需要编写可以同时与多个客户端保持连接的服务器。我写的内容如下:
Main
上课:
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();
}
}
它可以或多或少地起作用。但这种方法的缺点是什么?我怀疑那里有太多的劣势,但我无法抓住他们。
答案 0 :(得分:2)
问题在于您创建了无数个threads
,其中threads
是昂贵的资源。您应该使用ThreadPool来限制程序中创建的线程数。
请考虑使用Executors
而不是使用此低级代码In Oracle documentation about Executors, there is an example similar to what you doing. Check it out!
答案 1 :(得分:1)
话虽如此,如果你不使用你的主线程做什么,为什么不做类似的事情(并记住我也不是网络程序员)
public class ConnectionUtils {
protected boolean stop = false;
public static void waitForClients() {
while (!stop) {
Client c = new Client(server.accept());
new Thread(new ClientDelegate(c)).start();
}
}
}
public static class ClientDelegate implements Runnable {
private Client client;
public ClientDelegate(Client c) { this.client = c; }
public static void run() {
c.sendLine("Hello client\n");
}
}