Establishing the server
//server.js
varIO = require (' Socket.io ') (80);varChat =io. of ('/chat ')//Set namespace. On (' Connection ',function(socket) {Socket.emit (' A message ', {// this will only be sent to its own socket that:' Only ' , '/chat ': ' would get ' }); Chat.emit (' A message ', {// global send everyone:' In ' , '/chat ': ' would get ' }); });varNews =io. of ('/news '). On (' Connection ',function(socket) {Socket.emit (' Item ', {news: ' Item ' }); });
<script> var chat = io.connect (' http://localhost/chat ') // /chat/news Here is the namespace, It doesn't matter with the URL . = Io.connect (' http://localhost/news ');//can also be directly IO (), which will connect Chat.on based on your current URL ( function () { chat.emit (' hi! ' ); }); News.on (function () { news.emit (' woot '); }); </script>
Send Receipts
Server.js
var io = require (' Socket.io '),io.on (function (socket) { Socket.on ( function (name, fn) { fn (' woot '); });});
Client.js
<script> var// Tip:io () with no args does auto-discovery function // tip:you can avoid listening on ' connect ' and listen on events directly too! function (data) { ///emit function The third optional parameter is a callback function, which can have parameters, the call of the parameter is determined by the server // data Will is ' Woot ' }) ; </script>
Set the Sending object
// Send yourself socket.broadcase.emit () // Send to users outside of themselves Io.emit () // Send all Users io.of ()/io.to ()/ / users sending namespaces/rooms
Preliminary study on Socket.io