javascript - Node.js websocket.io 光标示例 我看不到它?

标签 javascript node.js websocket

我是 Node.js 新手,正在学习“粉碎 Node.js”一书的示例。在 websockets 章节中,我正在努力让这个示例发挥作用。请原谅我,这是一个非常简单的错误!我很困惑为什么即使使用作者的代码我也看不到光标?我从Github下载了源代码。

代码如下:(首先是server.js文件):

var express = require('express')
  , wsio = require('websocket.io')

/**
 * Create express app.
 */

var app = express.createServer();

/**
 * Attach websocket server.
 */

var ws = wsio.attach(app);

/**
 * Serve our code
 */

app.use(express.static('public'))

/**
 * Listening on connections
 */

var positions = {}
  , total = 0

ws.on('connection', function (socket) {
  // we give the socket an id
  socket.id = ++total;

  // we send the positions of everyone else
  socket.send(JSON.stringify(positions));

  socket.on('message', function (msg) {
    try {
      var pos = JSON.parse(msg);
    } catch (e) {
      return;
    }

    positions[socket.id] = pos;
    broadcast(JSON.stringify({ type: 'position', pos: pos, id: socket.id }));
  });

  socket.on('close', function () {
    delete positions[socket.id];
    broadcast(JSON.stringify({ type: 'disconnect', id: socket.id }));
  });

  function broadcast (msg) {
    for (var i = 0, l = ws.clients; i < l; i++) {
      // we avoid sending a message to the same socket that broadcasts
      if (socket.id != ws.clients[i].id) {
        // we call `send` on the other clients
        ws.clients[i].send(msg);
      }
    }
  }
});

/**
 * Listen
 */

app.listen(3000);

其次是./public/index.html文件的脚本内容:

<!doctype html>
<html>
  <head>
    <title>WebSocket cursors</title>
    <script src="onload">
      window.onload = function () {
        var ws = new WebSocket('ws://localhost:3000');

        ws.onopen = function () {
          document.onmousemove = function (ev) {
            ws.send(JSON.stringify({ x: ev.clientX, y: ev.clientY }));
          }
        }

        ws.onmessage = function (msg) {
          var obj = JSON.parse(msg);

          // the first message is the position of all existing cursors
          if (initialized) {
            initialized = true;
            for (var id in obj) {
              move(id, obj[i]);
            }
          } else {
            // other messages can either be a position change or
            // a disconnection
            if ('disconnect' == obj.type) {
              remove(obj.id);
            } else {
              move(obj.id, obj.pos);
            }
          }
        }

        function move (id, pos) {
          var cursor = document.getElementById('cursor-' + id);

          if (!cursor) {
            cursor = document.createElement('img');
            cursor.src = '/cursor.png';
            cursor.style.position = 'absolute';
            document.body.appendChild(cursor);
          }

          cursor.style.left = pos.x + 'px';
          cursor.style.top = pos.y + 'px';
        }

        function remove (id) {
          var cursor = document.getElementById('cursor-' + id);
          cursor.parentNode.removeChild(cursor);
        }
      }
    </script>
  </head>
  <body>
    <h1>WebSocket cursors</h1>
  </body>
</html>

最佳答案

我将 Express 框架从版本 2.x.x 更改为最新版本,并更新了我的 websocket.io。然后重写了我的代码。现在我可以成功运行它了。 这是我的代码:

服务器.js:

var express = require('express'),
    wsio = require('websocket.io'),
    port = 3000,
    app = express(),
    server = app.listen(port, function() {
        console.log('server listening on port ' + port);
    });

app.use(express.static('public'))
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

var ws = wsio.attach(server),
    positions = {},
    total = 0;

ws.on('connection', function(socket) {
    socket.id = ++total;

    socket.send(JSON.stringify(positions));

    socket.on('message', function(msg) {
        try {
            var pos = JSON.parse(msg);
        } catch (e) {
            return;
        }

        positions[socket.id] = pos;
        broadcast(JSON.stringify({
            type: 'position',
            pos: pos,
            id: socket.id
        }));
    });

    socket.on('close', function() {
        delete positions[socket.id];
        broadcast(JSON.stringify({
            type: 'disconnect',
            id: socket.id
        }));
    });

    function broadcast(msg) {
        for (var i = 0, l = ws.clients.length; i < l; i++) {
            if (ws.clients[i] && socket.id != ws.clients[i].id) {
                ws.clients[i].send(msg);
            }
        }
    }
});

和index.html:

<!doctype html>
<html>

<head>
    <title>WebSocket cursors</title>
    <script>
    window.onload = function() {
        var ws = new WebSocket('ws://localhost:3000');

        ws.onopen = function() {
            document.onmousemove = function(ev) {
                ws.send(JSON.stringify({
                    x: ev.clientX,
                    y: ev.clientY
                }));
            }
        }

        ws.onmessage = function(msg) {
            var obj = JSON.parse(msg.data),
                initialized = (obj.type) ? true : false;

            if (!initialized) {
                initialized = true;
                for (var id in obj) {
                    move(id, obj[id]);
                }
            } else {
                if ('disconnect' == obj.type) {
                    remove(obj.id);
                } else {
                    move(obj.id, obj.pos);
                }
            }
        }

        function move(id, pos) {
            var cursor = document.getElementById('cursor-' + id);

            if (!cursor) {
                cursor = document.createElement('img');
                cursor.src = '/cursor.png';
                cursor.id = 'cursor-' + id;
                cursor.style.position = 'absolute';
                document.body.appendChild(cursor);
            }

            cursor.style.left = pos.x + 'px';
            cursor.style.top = pos.y + 'px';
        }

        function remove(id) {
            var cursor = document.getElementById('cursor-' + id);
            if (cursor) cursor.parentNode.removeChild(cursor);
        }
    }
    </script>
</head>

<body>
    <h1>WebSocket cursors</h1>
</body>

</html>

关于javascript - Node.js websocket.io 光标示例 我看不到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42641670/

相关文章:

javascript - 在react中使用脚本标签会出现错误 "Unexpected token"

node.js - 基于 Mongoose 中另外两个字段的第三个字段的计算

javascript - WebSockets 如何处理 2 个或更多相同的用户窗口

php - 尝试以symfony中其访问权限禁止的方式访问套接字

javascript - 将逗号分隔值的字符串转换为多维 JavaScript 数组?

javascript - 更改将文件拖到网页上时工具提示的内容

javascript - 继续图像的滚动效果吗?

javascript - 如何以 jison 形式将附加输入传递给 `parse`?

javascript - 将数据从 React 传递到 Node Express 服务器

javascript - 两个用户之间的 Websocket session