我正在使用 Socket.io 编写游戏,但我遇到了问题,当服务器创建新的 img(新角色)时,我只能在一台计算机上看到它。在这种情况下,我想为每台连接的计算机看到相同数量的图像更好如果你看这个谢谢你的每一个帮助
服务器:
var handler = function(req, res) {
fs.readFile('./index.html', function (err, data) {
if(err) throw err;
res.writeHead(200);
res.end(data);
});
}
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var port = 3250;
app.listen(port);
var postacie = [];
var ile=0;
// socket.io
io.sockets.on('connection', function (socket) {
postacie[ile]=createChar();
ile++;
io.sockets.emit("tworz", postacie);
socket.on("disconnect", function()
{
postacie.splice(0, 1);
io.sockets.emit("tworz", postacie);
})
});
function createChar()
{
var postac = {
src: "http://img703.imageshack.us/img703/1416/2st.gif",
id: "character"
}
return postac;
}
客户:
<!DOCTYPE html>
<html>
<head>
<title>Real tie game</title>
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
window.onload = function() {
var socket = io.connect('http://localhost:3250');
socket.on("tworz", function(data)
{
for (var i=0; i < data.length; i++) {
var element = document.createElement('img');
element.src = data[i].src;
element.id = data[i].id;
var body = document.getElementsByTagName('body')
body.appendChild(element);
};
})
}
</script>
</head>
<body>
</body>
</html>