gpt4 book ai didi

node.js - Node.js 中的客户端-服务器通信

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:40 25 4
gpt4 key购买 nike

我最近开始使用 Node.js 来制作一个在线游戏(用于教育)。通过阅读各种教程,我想出了如下所示的简单代码。使用我拥有的代码,我能够进行客户端-服务器通信,这基本上是我制作游戏所需的全部内容。只有一个问题,只有客户端可以发起 session ,而服务器只能响应。除此之外,我还需要随时将当前的游戏状态从服务器发送到客户端。例如,在 2 人游戏中,当玩家发送更改游戏状态的命令时,需要将新的游戏状态转发给两个玩家。

node.js 中有一个简单的方法可以做到这一点吗?我知道您不能简单地向客户端发送消息,因为不能期望客户端打开端口供服务器使用,但也许有一种方法可以让客户端留下连接供服务器使用?我是那种通过例子学习的人,因此一些简单的工作代码将不胜感激。

顺便说一句,我正在 firebase 上托管游戏,以防相关。

index.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);

index.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>

最佳答案

我会为此使用 websockets。设置连接后,您可以从任一侧发起消息。 WS npm package让这变得非常容易。

服务器示例(使用 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!');
});

客户端示例(这里不需要任何包,它内置于大多数浏览器中):

// 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);
});

如果您无法使用 Websocket,还有其他选择,例如轮询(客户端定期调用服务器以查看是否有消息)和长轮询(服务器人为地长时间保持打开的 http 请求,直到消息准备好)。

关于node.js - Node.js 中的客户端-服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52407025/

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