0

我这里有一些(不完整的)代码用于客户端/服务器对,这是服务器类,但由于某种我不知道的原因,代码似乎停止运行 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();
    }
}
4

1 回答 1

3

ServerSocket.accept() 阻塞,直到与套接字建立连接。请参阅http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html#accept()。当客户端连接到您的套接字时,套接字将解除阻塞,您应该会看到“This won't print”。

于 2013-07-13T04:39:20.307 回答