//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() // 房间的用户