다중 스레드 서버 프로그램에 대한 연결을 열어 두려고합니다. 단추를 눌렀을 때 연결된 모든 클라이언트에 테스트 메시지를 보내고 싶습니다.A 소켓과의 지속적인 연결 유지
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();
}
누군가가 연결을 유지하고 데이터를 보낼 준비가되면 도와 주시면 감사하겠습니다.
'while (true) {sendUpdate (out);} 이렇게하면 많은 스레드를 생성 할 수 있습니다. 'setUpdate()'메쏘드 안에 새로운 쓰레드. –
소켓은 사용자 또는 클라이언트가 닫을 때까지 열린 상태로 유지됩니다. 루프를 스레드의'run' 메소드로 옮긴다. –
나는 그것을 도왔다. 그러나 도움이된다. 그러나 나의 cpu 사용은 접속 된 클라이언트 당 약 80 %로 간다, 나는 단 4 연결 만 할 수있다. – user1497561