我看过很多问题,但没有一个能解决我的问题。
这是我的JS(app.js)代码:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(2000);
console.log('Server has started.');
var socket_list = {};
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket) {
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list = socket.id = socket;
});
setInterval(function() {
for(var i in socket_list) {
var socket = socket_list[i];
socket.x++;
socket.y++;
socket.emit('newPosition', {
x: socket.x,
y: socket.y
});
}
}, 1000/25);
这是我的HTML(index.html)代码:
<!DOCTYPE html>
<html>
<head>
<title>Multiplayer | HTML5</title>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<canvas id="ctx" width="512" height="512" style="border: 1px solid #000;"></canvas>
<script type="text/javascript">
var ctx = document.getElementById('ctx').getContext('2d');
ctx.font = '24px Calibri';
var socket = io();
socket.on('newPosition', function(data) {
ctx.clearRect(0,0,500,500);
ctx.fillText('P', data.x, data.y);
})
</script>
</body>
</html>
我正在关注本教程:https://www.youtube.com/watch?v=_GioD4LpjMw&feature=youtu.be
已经3岁了,但一切进展顺利,直到视频^^中的4:47。
使用上面^^完全相同的代码,我得到了:
答案 0 :(得分:1)
您正在用Socket
对象替换Socket列表对象。还要使用io.on
。
io.sockets.on('connection', function(socket) {
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list = socket.id = socket;
});
您需要将其更改为
io.on('connection', function(socket) {//use io.on
console.log('Socket Connection');
socket.id = Math.random();
socket.x = 0;
socket.y = 0;
socket_list[socket.id] = socket;//fix this error
});
将io.emit
更改为socket.emit
。
socket.emit('newPosition', {
x: socket.x,
y: socket.y
});