代码之家  ›  专栏  ›  技术社区  ›  konstantin

在java中与服务器和客户端WebSocket正确通信

  •  0
  • konstantin  · 技术社区  · 7 年前

        try {
            serverSocket = new ServerSocket(10007);
        }
        catch (IOException e)
        {
            System.err.println("Could not listen on port: 10007.");
            System.exit(1);
        }
    
        System.out.println ("Waiting for connection.....");
    
        try {
            clientSocket = serverSocket.accept();
        }
        catch (IOException e)
        {
            System.err.println("Accept failed.");
            System.exit(1);
        }
        System.out.println ("Connection successful");
    

    当我试图从客户端连接时,似乎整个事情在我收到消息时都不起作用 waiting for connection... . 我连接客户端的代码如下:

     String serverHostname = new String("ip");
    
        if (args.length > 0)
            serverHostname = args[0];
        System.out.println("Attemping to connect to host " +
                serverHostname + " on port 10007.");
    
        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
    
        try {
            echoSocket = new Socket(serverHostname, 10007);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + serverHostname);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                    + "the connection to: " + serverHostname);
            System.exit(1);
        }
    

    这会是什么问题?

    1 回复  |  直到 7 年前
        1
  •  1
  •   francis94c    7 年前

    ServerSocket.accept(); 方法是一个锁定调用,这意味着程序执行将在此停止,直到客户端连接到它。

    if (args.length > 0)
        serverHostname = args[0];
    

    args[0] 可能不是ip地址,我不太确定java命令行应用程序的行为,但在c++中,正确上下文中的args[0]始终是程序可执行文件的绝对路径。java中可能也是这样。 因此,您可能会传递一个ip地址,但实际上会作为 args[1]