我在代码中添加了日志,只是为了了解其执行的顺序和时间,但是到目前为止,这只是令人困惑!
当我执行此代码并启动服务器时,我得到这些输出
“启动服务器”,“ ServerThread”
“侦听”,“ ServerThread”
“连接已到达”,“ ServerThread”
然后停在那里,当我连接到服务器时,我只会看到
“连接已接受”,“ ServerThread”
好像挂在上面
socket = serverSocket.accept();
退出尝试某种异常并再次打印整个内容,这是不是可以接受的?
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
Log.e("start server", "ServerThread");
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO error at starting server", "ServerThread");
} catch (Exception e) {
Log.e("Exc at starting server", "ServerThread");
}
while (!Thread.currentThread().isInterrupted()) {
Log.e("listening", "ServerThread");
try {
Log.e("connection arrived", "ServerThread");
socket = serverSocket.accept();
Log.e("connection accepted", "ServerThread");
CommunicationThread commThread = new CommunicationThread(
socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
Log.e("IO error at accept", "ServerThread");
} catch (Exception e) {
Log.e("Exc at accept", "ServerThread");
}
}
}
}
最佳答案
这是一种阻止程序方法,它将一直阻止,直到您收到连接为止。
看一下文档:http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#accept()