gpt4 book ai didi

javascript - 无法连接到 Google Cloud Compute Engine 上的 NodeJS WS 服务器

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:47 25 4
gpt4 key购买 nike

我创建了两个 JavaScript 文件(一个服务器文件和一个客户端文件)来组成一个小型多人游戏。当我使用 node server.js 在本地运行服务器文件时,它开始运行。然后我可以使用 node client.js 运行客户端文件来玩游戏,一切正常。但是,当我尝试在 linux 实例(谷歌云上的计算引擎)上实时托管游戏时,我无法从客户端连接到它。我正在使用 ws nodeJS 中的 websockets 库。

代码如下:

服务器.js

const WebSocket = require('ws');
const util = require('util');

const wss = new WebSocket.Server({ port: 8889 });

var magicNum = Math.ceil(Math.random() * 5);
var champion = "James";
var connections = [];

console.log('server listening...');

wss.on('connection', function connection(ws) {

connections.push({
ws: ws,
name: "",
score: 0
});

ws.on('message', function incoming(message, flags) {

var currentPlayer;

for (var i = 0; i < connections.length; i++) {
if (connections[i].ws === ws) {
currentPlayer = connections[i];
}
}

var response;
var obj = JSON.parse(message);

if (parseInt(obj.guess) === magicNum) {

currentPlayer.score++;
response = "HOLY COW! YOU GUESSED THE MAGIC NUMBER!!!" +
"I now declare you, " + obj.name + ", the new champion! (You have correctly guessed ( "
+ currentPlayer.score + " ) numbers)";
champion = obj.name;
magicNum = Math.ceil(Math.random() * 5);

ws.send(JSON.stringify({ response: response, prompt: true }));

for (var i = 0; i < connections.length; i++) {
if (connections[i].ws !== ws) {
response = "Uh oh, too slow! " + obj.name + " correctly guessed the number and is the new champion"
+ " with " + currentPlayer.score + " correct guesses!";
connections[i].ws.send(JSON.stringify({ response: response, prompt: false }))
}
}

} else {
response = "Sorry, that's not the magic number. The champion is still " + champion + ".";
ws.send(JSON.stringify({ response: response, prompt: true }));
}

});

ws.on('close', function (a, b) {

for (var i = 0; i < connections.length; i++) {
if (connections[i].ws === ws) {
connections.pop(i);
console.log('removing connection from array');
}
}
console.log('current connections now: ' + connections.length);
})
});

客户端.js

const WebSocket = require('ws');
var prompt = require('prompt');

//const ws = new WebSocket('ws://localhost:8889');
const ws = new WebSocket('ws://35.185.74.130:8889');

var clientName = '';

function beginPromptForGuess() {

var numberSchema = {
properties: {
number: {
description: 'Please guess an integer between 1 and 20',
pattern: /^\d+$/,
message: 'please enter an integer.',
required: true
}
}
};

console.log('prompt is: ' + prompt.stopped + " " + !prompt.started)

if (prompt.stopped || !prompt.started) {
console.log('starting prompt');

prompt.get(numberSchema, function (err, result) {
if (result) {
console.log('got number');
ws.send(JSON.stringify({ name: clientName, guess: result.number }));

}
})
}
}

ws.on('open', function open() {

setTimeout(function () {
console.log('Hey, let\'s play a game!');

var nameSchema = {
properties: {
name: {
description: 'First, what is your name?',
pattern: /^[a-zA-Z\s\-]+$/,
message: 'Name must be only letters, spaces, or dashes',
required: true
}
}
};

prompt.get(nameSchema, function (err, result) {
if (result) {
clientName = result.name;
console.log('Hi there, ' + result.name + '!');
console.log('Let\'s play!');
beginPromptForGuess();
}
});
}, 500);

});

ws.on('message', function incoming(data, flags) {
var obj = JSON.parse(data);
console.log('Server says: ' + obj.response);

if (obj.prompt) {
beginPromptForGuess();
}
});

在我创建 linux 实例并使用 SSH“在浏览器窗口中打开”选项在目录 home/mrjim 中打开实例内部的 shell 之后。该实例已经有 Node ,所以我将服务器代码粘贴到一个文件中,运行 npm init 来创建一个 package.json 文件,安装 ws 库。然后我运行了 node server.js,它似乎工作正常:

enter image description here

但是,当我尝试从客户端连接到它时,shell 会挂起一段时间并给出以下输出:

events.js:160
throw er; // Unhandled 'error' event
^

Error: connect ECONNREFUSED 35.185.74.130:80
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1085:14)

我是不是对服务器文件的位置做错了什么,或者我是如何编写 ip/端口的?谢谢。

此外,这是我的 Linux 实例的 Google 云配置: enter image description here

我也在防火墙规则中打开了端口,但我仍然无法从客户端连接:

enter image description here

最佳答案

在您的谷歌云设置的屏幕截图中,您似乎将外部 IP 设置为 *Ephemeral*。要从外部客户端(例如本地计算机的命令 shell)访问它,您应该将其更改为统计 ip。此外,对于多人游戏的后端,我建议使用更安全的 SSL 端口 443 而不是 8889。

祝你好运!

关于javascript - 无法连接到 Google Cloud Compute Engine 上的 NodeJS WS 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43020929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com