Java和套接字,代码不会继续

时间:2015-09-21 15:11:02

标签: java client-server

我不是这方面的专家,但下面的代码只打印消息“等待连接.....”,而不打印其他消息。为什么?没有异常并且线程正在运行,但是在调用accept()方法之后,它不会继续。

public static void main(String[] args) {
        try {
            ServerSocket serverSocket = null;

            try {
            serverSocket = new ServerSocket(0);//0 any free port
            } catch (IOException e) {
            System.err.println("Could not listen on port: xxx.");
            System.exit(1);
            }

            Socket clientSocket = null;
            System.out.println("Waiting for connection.....");

            //  try {
            clientSocket = serverSocket.accept();
            /*  } catch (IOException e) {
             System.err.println("Accept failed.");
             System.exit(1);
             }*/
             //And now there is no output, "Waiting for connection....." is the last one
            System.out.println("Connection successful");
            System.out.println("Waiting for input.....");

            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null) {
            System.out.println("Server: " + inputLine);
            out.println(inputLine);

            if (inputLine.equals("Bye.")) {
                break;
            }
            }

            out.close();
            in.close();
            clientSocket.close();
            serverSocket.close();

        } catch (IOException ex) {
            Logger.getLogger(Sockets.class.getName()).log(Level.SEVERE, null, ex);
        }

        }

1 个答案:

答案 0 :(得分:2)

代码适合我,只要我更新代码告诉我连接我的客户端的端口。尝试将等待消息更改为:

System.out.println("Waiting for connection on port " + serverSocket.getLocalPort() + ".....");

然后使用telnet连接到该端口:

telnet localhost <port number>

我得到它回应我的回报就好了。

您可以将所需的端口作为命令行参数传递,而不是简单地选择任意端口。