【发布时间】:2015-07-02 00:22:41
【问题描述】:
我希望设置一个简单的通信套接字,以通过命令行将消息从我的本地计算机 (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 实例之间发送简单的消息。
【问题讨论】:
-
如果你监听 8080 端口,你不应该在安全组中打开它让调用进入吗?使用“Telnet machine_IP 8080”检查您是否可以访问该端口上的服务器。如果不是,则存在网络(如安全组)问题。
-
@AdamOcsvari 将其作为答案而不是评论发布,以便他可以接受。这就是为什么他无法从安全组外部的 8080 端口连接的正确答案。
-
@greg_diesel,你错了。是的,该规则需要存在,但缺少安全组规则将永远导致“连接被拒绝”错误,如果发布的代码准确无误,添加规则将无法解决此问题。缺少规则将导致超时,因为当安全组未充分打开时,不会发送 TCP
RST数据包。传入的数据包只是被丢弃,这会导致“连接超时”错误——一种非常不同的故障模式。贴出的代码使用环回接口地址,不可能在不同主机之间工作。
标签: node.js sockets amazon-web-services amazon-ec2