【问题标题】:Java Networking - Connecting two computersJava Networking - 连接两台计算机
【发布时间】:2019-08-09 11:11:01
【问题描述】:

我正在尝试编写一个简单的客户端-服务器程序,它将客户端机器连接到服务器机器。

到目前为止,我的代码在 localhost 上运行良好,但是当我将客户端代码中的 ip 地址替换为服务器机器的本地 ip 地址时,没有完成连接。我想我对InetAddress 的理解是错误的。

Socket 连接代码:Client.java

InetAddress ip = InetAddress.getByName("my_ip_address");
Socket s = new Socket(ip, 9876); //<- where the connection timeout happens

【问题讨论】:

  • @ScaryWombat 是的,客户端和服务器上的端口或初始化为 9876
  • @Joni 我在Socket s = new Socket(ip, 9876); 出现错误:java.net.ConnectException: Connection timed out: connect
  • 您在企业网络中尝试吗?防火墙可能会阻止非标准端口访问。
  • @javapedia.net 我没有知识告诉你,有什么办法可以找到
  • 是linux客户端吗?尝试像“ncat IP_address port_number”这样的 nc 命令。尝试像 80 这样的标准端口,然后是非标准端口。如果标准端口工作,那么非标准端口可能存在防火墙问题。如果这没有帮助,请改用 machine-name 。 “ping ip”有用吗? NCAT 命令参考:linuxtechi.com/nc-ncat-command-examples-linux-systems

标签: java sockets networking ip-address inetaddress


【解决方案1】:

您不会像这样从String 调用getBytes() 来获取您的IP 地址;选项1:致电getByName(String) 喜欢

InetAddress ip = InetAddress.getByName("127.0.0.1");

选项 2:构造正确的byte[]。喜欢,

InetAddress ip = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });

【讨论】:

  • 感谢您的回复,我从另一个问题中发现了这一点。现在我遇到了连接超时
  • @AlexT 通用调试技术 - 使用 telnet 本地测试;检查充当服务器的机器上的防火墙设置;使用建议客户端的 telnet 进行测试。您应该能够telnet myserver 9876 并获得连接。
  • 如今的调试技术比黄金还值钱 :)
  • @AlexT 不是。 Ping 只能测试 icmp。不是你的插座。如果没有telnet,也可以用netcat调试(比较复杂)。
  • @ElliottFrisch 好吧,我尝试在客户端计算机上运行 telnet server_ip 9876 并得到:Could not open connection to the host, on port 9876: Connect failed
猜你喜欢
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
相关资源
最近更新 更多