javascript - nodejs的websocket.io做一个以鼠标光标样式的图片形式展示所有连接过来的用户光标的位置的小游戏,出现问题?
ringa_lee
ringa_lee 2017-04-11 12:31:05
0
2
425

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:

   WebSocket cursors  

WebSocket cursors

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

ringa_lee
ringa_lee

ringa_lee

全員に返信 (2)
巴扎黑

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

   WebSocket cursors  

WebSocket cursors

いいねを押す+0
    刘奇

    谢邀 可我还是菜鸡 不懂node呢 回答不了问题

    いいねを押す+0
      最新のダウンロード
      詳細>
      ウェブエフェクト
      公式サイト
      サイト素材
      フロントエンドテンプレート
      私たちについて 免責事項 Sitemap
      PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!