我正在编写一个服务器,只要它通过套接字发送命令,它就应该保持与客户端的连接。
每次接受新连接时soTimeout
都设置为60000
,套接字将传递给提交给线程池的Runnable。
这是接受新连接的主要线程:
ExecutorService tpl = Executors.newFixedThreadPool(10);
while (!isCancelled) {
try {
ServerSocket ss = new ServerSocket(PORT);
Socket socket = ss.accept();
socket.setSoTimeout(60000);
tpl.submit(new Player(socket));
} catch(SocketException ignored) {
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
这是Player的run()方法中的循环:
try(Socket socket = this.socket;
PrintWriter out = new PrintWriter(new OutputStreamWriter( socket.getOutputStream(), "UTF-8"), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"))) {
for(String msg = in.readLine(); msg != null; msg = in.readLine()){
String[] cmd = msg.split(":");
switch (cmd[0]) {
case: "MOVE":
//DO SOMETHING
break;
//...
}
}
} catch(SocketTimeoutException e){
game.removePlayer(this);
game.broadcast("LOGOUT:" + username)
} catch(IOException e){
e.printStackTrace()
}
问题是尽管客户端没有在套接字上写60秒,但并不总是捕获SocketTimeoutException。 我找不到一个模式,但我注意到连接的客户端越少,没有抛出异常的可能性