首页 > 解决方案 > 两台电脑之间的Socket连接

问题描述

我在这里尝试了 node.js 和 java 程序之间的非常基本的套接字通信。

当我尝试本地主机上提供的代码时,一切正常。但是当我使用另一台笔记本电脑连接时,我无法在服务器端收到任何消息。

基本上我把“localhost”改成了ip地址,如下图:

var net = require('net');

var client = net.connect(4444, myIp, function() {
    console.log("connected!");
});
client.setEncoding('utf8');
setInterval(function() {
  console.log("Writing....")
  var ret = client.write('Hello from node.js\n');
  console.log("Wrote", ret)
}, 1000);

服务器的代码保持不变。但我在服务器端没有看到任何输出,客户端也没有显示“已连接”消息。

我也尝试在服务器中修改代码。我server = new ServerSocket(4444)改为server = new ServerSocket(4444, 50, InetAddress.getByName(myIp))

public class SocketServer {

    public static final int port = 12345;
    private ServerSocket server;

    public void listen() {
        try {
            // server = new ServerSocket(4444);
            server = new ServerSocket(4444, 50, InetAddress.getByName(myIp));
        } catch (IOException e) {
            System.out.println("Could not listen on port 4444");
            System.exit(-1);
        }
        while(true){
             ... Same code here
        }
    }

    /* creating new server and call it's listen method */
    public static void main(String[] args) {
        new SocketServer().listen();
    }

但是得到了无法绑定到该 ip 的 IoException。

有关如何修改代码以在具有不同 ips 的两台笔记本电脑之间建立套接字连接的任何建议?

更新
(1)我个人认为我问的问题与这篇文章不同。我在本地主机上工作没有问题,但是在使用具有不同 ips 的两台机器时遇到问题。
(2) 我已检查我的笔记本电脑的防火墙是否已关闭。

标签: javanode.jssockets

解决方案


推荐阅读