设置简单的服务器/客户端套接字以在AWS EC2上进行通信

Eri*_*rik 3 sockets amazon-ec2 amazon-web-services node.js

我希望设置一个简单的通信套接字,通过命令行将消息从本地机器(Windows)发送到我的AWS EC2实例.我已经安装了EC2设置和节点.我的斗争是确定用于此通信的端口/主机.请参阅以下内容:

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

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);
Run Code Online (Sandbox Code Playgroud)

client.js(在我的本地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');
});
Run Code Online (Sandbox Code Playgroud)

请注意,我已将安全组设置如下: 在此输入图像描述

请注意,当我运行上面的代码时,EC2输出为:"服务器侦听127.0.0.1:8080"

但是,在我的Windows机器上运行的client.js有以下错误: 在此输入图像描述

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

Mic*_*bot 9

您永远无法连接到从机器外部侦听127.0.0.1的任何内容.这是环回接口,只能从机器本身访问...这可以解释为什么它在本地工作.

您看到"拒绝连接" - 不是因为您无法访问EC2实例 - 而是因为您没有尝试.您正试图在您自己的本地计算机上访问侦听器,而该计算机没有侦听.

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

并且,正如评论中所提到的,您还需要在入站安全组中允许TCP端口8080,否则您将收到"连接超时"错误,因为数据包将被丢弃(不会被拒绝,只是丢弃). EC2网络在入站安全组中没有匹配规则.