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

请注意,我已经设置了我的安全组,如下所示: 在这里输入图像描述

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

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

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

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

您看到“拒绝连接” – 不是因为您无法访问EC2实例 – 而是因为您没有尝试。 您正尝试访问您自己的本地计算机上的侦听器,而不是侦听。

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

而且,正如在评论中提到的那样,您还需要在入站安全组中允许TCP端口8080,否则将出现“连接超时”错误,因为数据包将被丢弃(不被拒绝,只是被丢弃) EC2networking在入站安全组中没有匹配的规则。