Node.js中的客户端-服务器通信 [英] Client-server communication in Node.js

查看:40
本文介绍了Node.js中的客户端-服务器通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've recently been getting in to node.js in order to make an online game (for education). Through reading various tutorials I've come up with the simple code shown below. With the code I have I'm capable of client-server communication, which is mostly all I need in order to make the game. There's only one problem, only the client can initiate conversation whereas the server can only respond. In addition to this, I also need to at any moment in time send the current game state from the server to the client. For example, in a 2 player game, when a player sends a command that alters the game state, that new game state needs to be forwarded to BOTH players.

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

Is there a simple way in node.js to do this? I know that you can't simply send a message to the client since the client cannot be expected to have a port opened for the server to use, but maybe there's a way for the client to leave behind a connection for the server to use? I'm the kind of guy that learns by example, thus some simple working code would be appreciated.

顺便说一句,如果相关的话,我正在将游戏托管在Firebase上.

Btw, I'm hosting the game on firebase, in case that's relevant.

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:

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>

推荐答案

Firebase实时数据库是另一种选择.

The Firebase Realtime Database is another alternative.

https://github.com/firebase/quickstart-js/blob/master/database/scripts/main.js

<!-- index.html file in client browser -->
<script src="/__/firebase/5.5.0/firebase-app.js"></script>
<script src="/__/firebase/5.5.0/firebase-auth.js"></script>
<script src="/__/firebase/5.5.0/firebase-database.js"></script>
<script src="/__/firebase/init.js"></script>

<script src="scripts/main.js"></script>

<!-- main.js file in client browser -->
// Create new comment.
// createNewComment, commentInput, addCommentForm is defined in the main.js
addCommentForm.onsubmit = function(e) {
    e.preventDefault();
    createNewComment(postId, firebase.auth().currentUser.displayName, uid, commentInput.value);
    commentInput.value = '';
    commentInput.parentElement.MaterialTextfield.boundUpdateClassesHandler();
};
// Listen for comments.
// addCommentElement, postElement is defined in the main.js
var commentsRef = firebase.database().ref('post-comments/' + postId);
commentsRef.on('child_added', function(data) {
    addCommentElement(postElement, data.key, data.val().text, data.val().author);
});

这篇关于Node.js中的客户端-服务器通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆