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

时间:2018-09-19 13:27:45

标签: node.js firebase express

我最近开始涉足node.js,以便制作在线游戏(用于教育)。通过阅读各种教程,我得出了如下所示的简单代码。有了代码,我就能够进行客户端与服务器之间的通信,而这正是制作游戏所需的全部。只有一个问题,只有客户端可以发起对话,而服务器只能响应。除此之外,我还需要随时将当前游戏状态从服务器发送到客户端。例如,在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>

2 个答案:

答案 0 :(得分:0)

我将为此使用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);
});

如果您无法使用网络套接字,则可以使用其他方法,例如轮询(客户端定期调用服务器以查看是否有消息)和长轮询(服务器将人为地将http请求保持打开状态)直到消息准备就绪的时间。

答案 1 :(得分:0)

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

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