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

时间:2015-04-23 16:52:45

标签: node.js sockets amazon-web-services amazon-ec2

我希望设置一个简单的通信套接字,通过命令行将消息从本地计算机(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);

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');
});

请注意,我已将安全组设置如下: enter image description here

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

但是,在我的Windows机器上运行的client.js有以下错误: enter image description here

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

1 个答案:

答案 0 :(得分:9)

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

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

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

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

相关问题