Socket.IO初探
建立Server
//server.js
var io = require('socket.io')(80); var chat = io .of('/chat') //设定命名空间 .on('connection', function (socket) { socket.emit('a message', { //这个只会发送给自己的socket that: 'only' , '/chat': 'will get' }); chat.emit('a message', { //全局发送 everyone: 'in' , '/chat': 'will get' }); }); var news = io .of('/news') .on('connection', function (socket) { socket.emit('item', { news: 'item' }); });
<script> var chat = io.connect('http://localhost/chat') //这里的/chat /news 就是命名空间,跟URL没关系喔 , news = io.connect('http://localhost/news'); //也可以直接io(),这样会根据你当前的URL来连接 chat.on('connect', function () { chat.emit('hi!'); }); news.on('news', function () { news.emit('woot'); }); </script>
发送回执
//server.js
var io = require('socket.io')(80); io.on('connection', function (socket) { socket.on('ferret', function (name, fn) { fn('woot'); }); });
client.js
<script> var socket = io(); // TIP: io() with no args does auto-discovery socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too! socket.emit('ferret', 'tobi', function (data) { //emit函数第三个可选参数是一个回调函数,其可以有参数,参数的调用由服务器决定 console.log(data); // data will be 'woot' }); }); </script>
设定发送对象
socket.emit() //发送自己 socket.broadcase.emit() //发送到出自己以外的用户 io.emit() //发送全部用户 io.of() //设置命名空间
io.to() // 房间的用户