首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js中的客户端-服务器通信

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

Stack Overflow用户
提问于 2018-09-19 21:27:45
回答 1查看 5K关注 0票数 3

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

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

顺便说一句,我在firebase上托管这个游戏,如果这是相关的话。

index.js:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<!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>
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52407025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档