Fre*_*orp 5 node.js express firebase
我最近开始使用 Node.js 来制作一个在线游戏(用于教育)。通过阅读各种教程,我想出了如下所示的简单代码。使用我拥有的代码,我能够进行客户端-服务器通信,这基本上是我制作游戏所需的全部内容。只有一个问题,只有客户端可以发起会话,而服务器只能响应。除此之外,我还需要随时将当前的游戏状态从服务器发送到客户端。例如,在 2 人游戏中,当玩家发送更改游戏状态的命令时,需要将新的游戏状态转发给两个玩家。
Node.js 有没有一种简单的方法可以做到这一点?我知道您不能简单地向客户端发送消息,因为不能期望客户端打开端口供服务器使用,但也许有一种方法可以让客户端留下连接供服务器使用?我是那种通过例子学习的人,因此一些简单的工作代码将不胜感激。
顺便说一句,我正在 firebase 上托管游戏,以防相关。
索引.js:
const functions = require('firebase-functions');
const express = require('express');
const app = express();
app.post('/game', (request, response) => {
request.body.randomNumber = Math.random();
console.log(request.body);
response.json(request.body);
});
exports.app = functions.https.onRequest(app);
Run Code Online (Sandbox Code Playgroud)
索引.html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" id="commandbox" onkeypress="send(this)">
<br>
<div id="display"></div>
<script>
const send = (ele) => {
if (event.key === 'Enter') {
console.log(ele.value);
const json = {
name: "John",
gender: "male",
age: 25,
message: ele.value
};
postToGame(json);
}
};
</script>
<script>
const postToGame = (json) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", '/game', true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onload = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("display").innerHTML = xhr.responseText;
}
};
xhr.send(JSON.stringify(json));
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我会为此使用 websockets。设置连接后,您可以从任一侧发起消息。WS npm 包使这变得非常简单。
服务器示例(使用 ws npm 包):
const WebSocket = require('ws');
// Set up server
const wss = new WebSocket.Server({ port: 8080 });
// Wire up some logic for the connection event (when a client connects)
wss.on('connection', function connection(ws) {
// Wire up logic for the message event (when a client sends something)
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
// Send a message
ws.send('Hello client!');
});
Run Code Online (Sandbox Code Playgroud)
客户端示例(这里不需要任何包,它内置于大多数浏览器中):
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
Run Code Online (Sandbox Code Playgroud)
如果您无法使用 websocket,还有其他选择,例如轮询(客户端定期调用服务器以查看是否有消息)和长轮询(服务器人为地长时间保持打开的 http 请求)直到消息准备好)。