我在这里有一些(不完整的)代码用于客户端/服务器对,这里是服务器类,但由于某些原因我不知道代码似乎停止在serverSocket.accept()下面运行任何东西
我做错了什么? 感谢
class MPTagServer{
public String serverName = "MPTag Server";
public int gSize = 16;
public int maxPlayers = 16;
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
MPTagServer(String sn, int gs, int mp){
serverName = sn;
gSize = gs;
maxPlayers = mp;
}
public void start() throws Exception{
Task serverTask = new Task<Void>(){
@Override protected Void call() throws Exception{
int port = 6789;
try{
serverSocket = new ServerSocket(port);
}
catch(IOException e){
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
try{
System.out.println("This will print");
clientSocket = serverSocket.accept(); //Code won't run below here
System.out.println("This won't print");
}
catch(IOException e){
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
ComProtocol cp = new ComProtocol();
outputLine = cp.init();
out.println(outputLine);
out.close();
in.close();
clientSocket.close();
serverSocket.close();
return null;
}
};
Thread serverThread = new Thread(serverTask);
serverThread.setDaemon(true);
serverThread.start();
}
}
答案 0 :(得分:3)
ServerSocket.accept()阻塞,直到与套接字建立连接。见http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html#accept()。当客户端连接到您的套接字时,套接字将解除阻塞,您应该看到“这将不会打印”。