javascript - nodejs的websocket.io做一个以鼠标光标样式的图片形式展示所有连接过来的用户光标的位置的小游戏,出现问题?

查看:152
本文介绍了javascript - nodejs的websocket.io做一个以鼠标光标样式的图片形式展示所有连接过来的用户光标的位置的小游戏,出现问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

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>

运行后却无法看到光标,我用的书上源码也无法解决问题。疑惑好久了,求解答?

解决方案

server.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 - nodejs的websocket.io做一个以鼠标光标样式的图片形式展示所有连接过来的用户光标的位置的小游戏,出现问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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