簡體   English   中英

設置簡單的服務器/客戶端套接字以在AWS EC2上進行通信

[英]Setting up simple Server/Client Socket for communication on 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的任何內容。 這是環回接口,只能從機器本身訪問...這可以解釋為什么它在本地工作。

您看到“拒絕連接” - 不是因為您無法訪問EC2實例 - 而是因為您沒有嘗試。 您正試圖在您自己的本地計算機上訪問偵聽器,而該計算機沒有偵聽。

在服務器上,在主機0.0.0.0上綁定(偵聽),在客戶端上,連接到服務器的公共IP地址(如果有VPN,則連接到私有IP地址)。

並且,正如評論中所提到的,您還需要在入站安全組中允許TCP端口8080,否則您將收到“連接超時”錯誤,因為數據包將被丟棄(不會被拒絕,只是丟棄) EC2網絡在入站安全組中沒有匹配規則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM