1
我正试图保持多线程服务器程序的连接打开状态。当我点击一个按钮时,我希望它向所有连接的客户端发送测试消息。与套接字保持连接
public void run() {
try {
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream());
readUpdate(out, in);
while(true){sendUpdate(out);}
} catch (Exception e) {
e.printStackTrace();
}
}
使用多CPU的方式。
这是我的sendUpdate方法。
private void sendUpdate(final PrintWriter out) {
new Thread(new Runnable() {
public void run() {
if(Server.send) {
try {
if (Server.command != "idle") {
System.out.println("Sending");
out.println("[email protected]" + Server.command);
out.flush();
Server.send = false;
Thread.sleep(100);
}
} catch (Exception ex) {
}
}
}
}).start();
}
如果有人可以帮助我保持连接打开,并准备发送数据,我将不胜感激。
'而(真){sendUpdate(出);}'创造这么多线程这个产量:o ..只是不创建'setUpdate()'方法中的新线程。 – 2012-07-08 16:19:38
套接字将保持打开状态,直到您或客户端关闭它为止。将循环移到线程的'run'方法中。 – 2012-07-08 16:46:34
我试过了,我帮了忙,但是我的CPU使用率每个客户端连接了大约80%,我只能连接四个。 – user1497561 2012-07-08 16:53:54