为 AWS EC2 上的通信设置简单的 Server/Client 套接字

Setting up simple Server/Client Socket for communication on AWS EC2

我希望设置一个简单的通信套接字,以通过命令行将消息从我的本地计算机 (Windows) 发送到我的 AWS EC2 实例。我已经安装了 EC2 设置和节点。我的难题是确定使用哪个 Port/Host 进行此通信。请看以下内容:

server.js(在 AWS EC2 上 运行ning):

var net = require('net');

var HOST = '127.0.0.1'; 
var PORT = 8080;

// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {

    // We have a connection - a socket object is assigned to the connection automatically
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {

        console.log('DATA: ' + data);
        // Write the data back to the socket, the client will receive it as data from the server
        sock.write('You said: "' + data + '"');

    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        //console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

client.js(运行ning 在我的本地 windows 机器上):

var net = require('net');

var HOST = '127.0.0.1'; 
var PORT = 8080;

var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
    client.write('I am Chuck Norris!');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();

});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

请注意,我已按如下方式设置我的安全组:

注意当我运行上面的代码时,EC2输出是: "Server listening on 127.0.0.1:8080"

但是我的Windows机器上的client.js运行ning出现如下错误:

当 server.js 和 client.js 都是本地的 运行 时,这个简单的示例有效。请提供任何指导帮助,以便我可以在我的 Windows 机器和我的 EC2 实例之间发送简单的消息。

您将永远无法从计算机外部连接到正在侦听 127.0.0.1 的任何设备。那是环回接口,只能从机器本身访问……这可以解释为什么它在本地工作。

您看到 "connection refused"——不是因为您无法访问 EC2 实例——而是因为您没有尝试访问。您正在尝试访问您自己的本地计算机上的侦听器,但它没有在侦听。

在服务器上,绑定(侦听)主机 0.0.0.0,在客户端上,连接到服务器的 public IP 地址(如果您有 VPN,则为私有地址)。

而且,正如评论中提到的,您还需要在入站安全组中允许 TCP 端口 8080,否则您将收到 "connection timed out" 错误,因为数据包将被丢弃(不是拒绝,只是丢弃)在入站安全组中没有匹配规则的 EC2 网络边缘。