我創建了兩個構成小型多人遊戲的JavaScript文件(服務器文件和客戶端文件)。當我使用node server.js
在本地運行服務器文件時,它開始運行。然後,我可以用node client.js
運行客戶端文件來玩遊戲,並且一切正常。但是,當我嘗試在Linux實例(谷歌雲上的計算引擎)上實況託管遊戲時,我無法從客戶端連接到它。我正在爲nodeJS中的websockets使用ws庫。無法連接到Google雲計算引擎上的NodeJS WS服務器
下面是代碼:
server.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);
})
});
client.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。該實例已有節點,因此我將服務器代碼粘貼到文件中,運行npm init
以創建package.json文件,安裝了ws庫。然後我跑node server.js
,它似乎是工作:
然而,當我嘗試從外殼掛了一段時間的客戶端連接到它,並給這個輸出:
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 /端口有問題嗎?謝謝。
我也曾在防火牆規則開放的端口,但我仍然無法從客戶端連接:
看起來像你的IP範圍是你的內部IP。找到你的公共IP地址。 (你可以通過在chrome標籤中輸入「我的IP是什麼」來檢查這一點。)在你的IP範圍內添加這個。否則,通過提供您的ip爲0.0.0.0/0來允許所有請求。它爲我工作。請檢查。 – Balu