服务器(app.js)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
客户端(index.html)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
function onConnect(socket){
// sending to the client 发送到客户端
socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
// sending to all clients except sender发送给除发送方之外的所有客户端
socket.broadcast.emit('broadcast', 'hello friends!');
// sending to all clients in 'game' room except sender发送到“游戏”房间的所有客户端,除了发送者
socket.to('game').emit('nice game', "let's play a game");
// sending to all clients in 'game1' and/or in 'game2' room, except sender发送到“game1”和/或“游戏2”房间的所有客户端,除了发送者
socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");
// sending to all clients in 'game' room, including sender发送到“游戏”房间的所有客户端,包括发送者
io.in('game').emit('big-announcement', 'the game will start soon');
// sending to all clients in namespace 'myNamespace', including sender发送到名称空间“myNamespace”的所有客户端,包括发送者
io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');
// sending to individual socketid (private message)发送到单个的socketid(私有消息)
socket.to(<socketid>).emit('hey', 'I just met you');
// sending with acknowledgement发送和确认
socket.emit('question', 'do you think so?', function (answer) {});
// sending without compression发送不压缩
socket.compress(false).emit('uncompressed', "that's rough");
// sending a message that might be dropped if the client is not ready to receive messages发送消息,如果客户端不准备接收消息,可能会被删除
socket.volatile.emit('maybe', 'do you really need it?');
// sending to all clients on this node (when using multiple nodes)发送到该节点上的所有客户机(使用多个节点)
io.local.emit('hi', 'my lovely babies');
};