【问题标题】:Java and sockets, the code doesn´t continueJava 和套接字,代码不会继续
【发布时间】:2015-09-21 15:11:01
【问题描述】:

我不是这方面的专家,但下面的代码只打印消息“等待连接.....”,而不打印其他消息。为什么?没有异常,线程正在运行,但是调用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);
        }

        }

【问题讨论】:

  • 你怎么知道它监听哪个端口以便向它发送一些数据?
  • 你在打开一个socket到服务器后写了什么吗?创建 Socket clientSocket = new Socket(ip,port) 的客户端代码在哪里?创建clinetSocket后,打开输出流并写入东西,然后Server可以在InputStream中获取

标签: java client-server


【解决方案1】:

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

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

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

telnet localhost <port number>

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

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

【讨论】:

    猜你喜欢
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多