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

Java and sockets, the code doesn´t continue

我不是这方面的专家,但下面的代码代码只打印消息 "Waiting for connection.....",不打印其他消息。为什么?没有异常,线程是运行,但是调用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);
        }

        }

代码对我有用,前提是我更新了代码以告诉我将客户端连接到的端口。尝试将等待消息更改为:

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

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

telnet localhost <port number>

我得到它回显我的输入就好了。

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