{"id":8086,"date":"2015-11-26T13:35:16","date_gmt":"2015-11-26T13:35:16","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/11\/26\/automattic-socket-io\/"},"modified":"2022-08-30T15:03:01","modified_gmt":"2022-08-30T15:03:01","slug":"automattic-socket-io","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2015\/11\/26\/automattic-socket-io\/","title":{"rendered":"Automattic\/socket.io"},"content":{"rendered":"<p><img decoding=\"async\" src=\"http:\/\/secure.travis-ci.org\/Automattic\/socket.io.svg\" \/> <img decoding=\"async\" src=\"http:\/\/badge.fury.io\/js\/socket.io.svg\" \/> <img decoding=\"async\" src=\"http:\/\/img.shields.io\/npm\/dm\/socket.io.svg?style=flat\" \/> <img decoding=\"async\" src=\"http:\/\/slack.socket.io\/badge.svg\" \/><\/p>\n<h2>How to use<\/h2>\n<p>The following example attaches socket.io to a plain Node.JS HTTP server listening on port <code>3000<\/code>.<\/p>\n<pre><code>var server = require('http').createServer();\nvar io = require('socket.io')(server);\nio.on('connection', function(socket){\n  socket.on('event', function(data){});\n  socket.on('disconnect', function(){});\n});\nserver.listen(3000);\n<\/code><\/pre>\n<h3>Standalone<\/h3>\n<pre><code>var io = require('socket.io')();\nio.on('connection', function(socket){});\nio.listen(3000);\n<\/code><\/pre>\n<h3>In conjunction with Express<\/h3>\n<p>Starting with <strong>3.0<\/strong>, express applications have become request handler functions that you pass to <code>http<\/code> or <code>http<\/code> <code>Server<\/code> instances. You need to pass the <code>Server<\/code> to <code>socket.io<\/code>, and not the express application function.<\/p>\n<pre><code>var app = require('express')();\nvar server = require('http').createServer(app);\nvar io = require('socket.io')(server);\nio.on('connection', function(){ \/* \u2026 *\/ });\nserver.listen(3000);\n<\/code><\/pre>\n<h3>In conjunction with Koa<\/h3>\n<p>Like Express.JS, Koa works by exposing an application as a request handler function, but only by calling the <code>callback<\/code> method.<\/p>\n<pre><code>var app = require('koa')();\nvar server = require('http').createServer(app.callback());\nvar io = require('socket.io')(server);\nio.on('connection', function(){ \/* \u2026 *\/ });\nserver.listen(3000);\n<\/code><\/pre>\n<h2>API<\/h2>\n<h3>Server<\/h3>\n<p>Exposed by <code>require('socket.io')<\/code>.<\/p>\n<h3>Server()<\/h3>\n<p>Creates a new <code>Server<\/code>. Works with and without <code>new<\/code>:<\/p>\n<pre><code>var io = require('socket.io')();\n\/\/ or\nvar Server = require('socket.io');\nvar io = new Server();\n<\/code><\/pre>\n<h3>Server(opts:Object)<\/h3>\n<p>Optionally, the first or second argument (see below) of the <code>Server<\/code> constructor can be an options object.<\/p>\n<p>The following options are supported:<\/p>\n<ul>\n<li><code>serveClient<\/code> sets the value for Server#serveClient()<\/li>\n<li><code>path<\/code> sets the value for Server#path()<\/li>\n<\/ul>\n<p>The same options passed to socket.io are always passed to the <code>engine.io<\/code> <code>Server<\/code> that gets created. See engine.io options as reference.<\/p>\n<h3>Server(srv:http#Server, opts:Object)<\/h3>\n<p>Creates a new <code>Server<\/code> and attaches it to the given <code>srv<\/code>. Optionally <code>opts<\/code> can be passed.<\/p>\n<h3>Server(port:Number, opts:Object)<\/h3>\n<p>Binds socket.io to a new <code>http.Server<\/code> that listens on <code>port<\/code>.<\/p>\n<h3>Server#serveClient(v:Boolean):Server<\/h3>\n<p>If <code>v<\/code> is <code>true<\/code> the attached server (see <code>Server#attach<\/code>) will serve the client files. Defaults to <code>true<\/code>.<\/p>\n<p>This method has no effect after <code>attach<\/code> is called.<\/p>\n<pre><code>\/\/ pass a server and the `serveClient` option\nvar io = require('socket.io')(http, { serveClient: false });\n\n\/\/ or pass no server and then you can call the method\nvar io = require('socket.io')();\nio.serveClient(false);\nio.attach(http);\n<\/code><\/pre>\n<p>If no arguments are supplied this method returns the current value.<\/p>\n<h3>Server#path(v:String):Server<\/h3>\n<p>Sets the path <code>v<\/code> under which <code>engine.io<\/code> and the static files will be served. Defaults to <code>\/socket.io<\/code>.<\/p>\n<p>If no arguments are supplied this method returns the current value.<\/p>\n<h3>Server#adapter(v:Adapter):Server<\/h3>\n<p>Sets the adapter <code>v<\/code>. Defaults to an instance of the <code>Adapter<\/code> that ships with socket.io which is memory based. See socket.io-adapter.<\/p>\n<p>If no arguments are supplied this method returns the current value.<\/p>\n<h3>Server#origins(v:String):Server<\/h3>\n<p>Sets the allowed origins <code>v<\/code>. Defaults to any origins being allowed.<\/p>\n<p>If no arguments are supplied this method returns the current value.<\/p>\n<h3>Server#origins(v:Function):Server<\/h3>\n<p>Sets the allowed origins as dynamic function. Function takes two arguments <code>origin:String<\/code> and <code>callback(error, success)<\/code>, where <code>success<\/code> is a boolean value indicating whether origin is allowed or not.<\/p>\n<p><strong>Potential drawbacks<\/strong>:<\/p>\n<ul>\n<li>in some situations, when it is not possible to determine <code>origin<\/code> it may have value of <code>*<\/code><\/li>\n<li>As this function will be executed for every request, it is advised to make this function work as fast as possible<\/li>\n<li>If <code>socket.io<\/code> is used together with <code>Express<\/code>, the CORS headers will be affected only for <code>socket.io<\/code> requests. For Express can use cors<\/li>\n<\/ul>\n<h3>Server#sockets:Namespace<\/h3>\n<p>The default (<code>\/<\/code>) namespace.<\/p>\n<h3>Server#attach(srv:http#Server, opts:Object):Server<\/h3>\n<p>Attaches the <code>Server<\/code> to an engine.io instance on <code>srv<\/code> with the supplied <code>opts<\/code> (optionally).<\/p>\n<h3>Server#attach(port:Number, opts:Object):Server<\/h3>\n<p>Attaches the <code>Server<\/code> to an engine.io instance that is bound to <code>port<\/code> with the given <code>opts<\/code> (optionally).<\/p>\n<h3>Server#listen<\/h3>\n<p>Synonym of <code>Server#attach<\/code>.<\/p>\n<h3>Server#bind(srv:engine#Server):Server<\/h3>\n<p>Advanced use only. Binds the server to a specific engine.io <code>Server<\/code> (or compatible API) instance.<\/p>\n<h3>Server#onconnection(socket:engine#Socket):Server<\/h3>\n<p>Advanced use only. Creates a new <code>socket.io<\/code> client from the incoming engine.io (or compatible API) <code>socket<\/code>.<\/p>\n<h3>Server#of(nsp:String):Namespace<\/h3>\n<p>Initializes and retrieves the given <code>Namespace<\/code> by its pathname identifier <code>nsp<\/code>.<\/p>\n<p>If the namespace was already initialized it returns it right away.<\/p>\n<h3>Server#emit<\/h3>\n<p>Emits an event to all connected clients. The following two are equivalent:<\/p>\n<pre><code>var io = require('socket.io')();\nio.sockets.emit('an event sent to all connected clients');\nio.emit('an event sent to all connected clients');\n<\/code><\/pre>\n<p>For other available methods, see <code>Namespace<\/code> below.<\/p>\n<h3>Server#close<\/h3>\n<p>Closes socket server<\/p>\n<pre><code>var Server = require('socket.io');\nvar PORT   = 3030;\nvar server = require('http').Server();\n\nvar io = Server(PORT);\n\nio.close(); \/\/ Close current server\n\nserver.listen(PORT); \/\/ PORT is free to use\n\nio = Server(server);\n<\/code><\/pre>\n<h3>Server#use<\/h3>\n<p>See <code>Namespace#use<\/code> below.<\/p>\n<h3>Namespace<\/h3>\n<p>Represents a pool of sockets connected under a given scope identified by a pathname (eg: <code>\/chat<\/code>).<\/p>\n<p>By default the client always connects to <code>\/<\/code>.<\/p>\n<h4>Events<\/h4>\n<ul>\n<li>\n<p><code>connection<\/code> \/ <code>connect<\/code>. Fired upon a connection.<\/p>\n<p>Parameters:<\/p>\n<ul>\n<li><code>Socket<\/code> the incoming socket.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h3>Namespace#name:String<\/h3>\n<p>The namespace identifier property.<\/p>\n<h3>Namespace#connected:Object<\/h3>\n<p>Hash of <code>Socket<\/code> objects that are connected to this namespace indexed by <code>id<\/code>.<\/p>\n<h3>Namespace#clients(fn:Function)<\/h3>\n<p>Gets a list of client IDs connected to this namespace (across all nodes if applicable).<\/p>\n<p>An example to get all clients in a namespace:<\/p>\n<pre><code>var io = require('socket.io')();\nio.of('\/chat').clients(function(error, clients){\n  if (error) throw error;\n  console.log(clients); \/\/ =&gt; [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]\n});\n<\/code><\/pre>\n<p>An example to get all clients in namespace\u2019s room:<\/p>\n<pre><code>var io = require('socket.io')();\nio.of('\/chat').in('general').clients(function(error, clients){\n  if (error) throw error;\n  console.log(clients); \/\/ =&gt; [Anw2LatarvGVVXEIAAAD]\n});\n<\/code><\/pre>\n<p>As with broadcasting, the default is all clients from the default namespace (\u2019\/\u2019):<\/p>\n<pre><code>var io = require('socket.io')();\nio.clients(function(error, clients){\n  if (error) throw error;\n  console.log(clients); \/\/ =&gt; [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]\n});\n<\/code><\/pre>\n<h3>Namespace#use(fn:Function):Namespace<\/h3>\n<p>Registers a middleware, which is a function that gets executed for every incoming <code>Socket<\/code> and receives as parameter the socket and a function to optionally defer execution to the next registered middleware.<\/p>\n<pre><code>var io = require('socket.io')();\nio.use(function(socket, next){\n  if (socket.request.headers.cookie) return next();\n  next(new Error('Authentication error'));\n});\n<\/code><\/pre>\n<p>Errors passed to middleware callbacks are sent as special <code>error<\/code> packets to clients.<\/p>\n<h3>Socket<\/h3>\n<p>A <code>Socket<\/code> is the fundamental class for interacting with browser clients. A <code>Socket<\/code> belongs to a certain <code>Namespace<\/code> (by default <code>\/<\/code>) and uses an underlying <code>Client<\/code> to communicate.<\/p>\n<h3>Socket#rooms:Array<\/h3>\n<p>A list of strings identifying the rooms this socket is in.<\/p>\n<h3>Socket#client:Client<\/h3>\n<p>A reference to the underlying <code>Client<\/code> object.<\/p>\n<h3>Socket#conn:Socket<\/h3>\n<p>A reference to the underlying <code>Client<\/code> transport connection (engine.io <code>Socket<\/code> object).<\/p>\n<h3>Socket#request:Request<\/h3>\n<p>A getter proxy that returns the reference to the <code>request<\/code> that originated the underlying engine.io <code>Client<\/code>. Useful for accessing request headers such as <code>Cookie<\/code> or <code>User-Agent<\/code>.<\/p>\n<h3>Socket#id:String<\/h3>\n<p>A unique identifier for the socket session, that comes from the underlying <code>Client<\/code>.<\/p>\n<h3>Socket#emit(name:String[, \u2026]):Socket<\/h3>\n<p>Emits an event to the socket identified by the string <code>name<\/code>. Any other parameters can be included.<\/p>\n<p>All datastructures are supported, including <code>Buffer<\/code>. JavaScript functions can\u2019t be serialized\/deserialized.<\/p>\n<pre><code>var io = require('socket.io')();\nio.on('connection', function(socket){\n  socket.emit('an event', { some: 'data' });\n});\n<\/code><\/pre>\n<h3>Socket#join(name:String[, fn:Function]):Socket<\/h3>\n<p>Adds the socket to the <code>room<\/code>, and fires optionally a callback <code>fn<\/code> with <code>err<\/code> signature (if any).<\/p>\n<p>The socket is automatically a member of a room identified with its session id (see <code>Socket#id<\/code>).<\/p>\n<p>The mechanics of joining rooms are handled by the <code>Adapter<\/code> that has been configured (see <code>Server#adapter<\/code> above), defaulting to socket.io-adapter.<\/p>\n<h3>Socket#leave(name:String[, fn:Function]):Socket<\/h3>\n<p>Removes the socket from <code>room<\/code>, and fires optionally a callback <code>fn<\/code> with <code>err<\/code> signature (if any).<\/p>\n<p><strong>Rooms are left automatically upon disconnection<\/strong>.<\/p>\n<p>The mechanics of leaving rooms are handled by the <code>Adapter<\/code> that has been configured (see <code>Server#adapter<\/code> above), defaulting to socket.io-adapter.<\/p>\n<h3>Socket#to(room:String):Socket<\/h3>\n<h3>Socket#in(room:String):Socket<\/h3>\n<p>Sets a modifier for a subsequent event emission that the event will only be <em>broadcasted<\/em> to sockets that have joined the given <code>room<\/code>.<\/p>\n<p>To emit to multiple rooms, you can call <code>to<\/code> several times.<\/p>\n<pre><code>var io = require('socket.io')();\nio.on('connection', function(socket){\n  socket.to('others').emit('an event', { some: 'data' });\n});\n<\/code><\/pre>\n<h3>Socket#compress(v:Boolean):Socket<\/h3>\n<p>Sets a modifier for a subsequent event emission that the event data will only be <em>compressed<\/em> if the value is <code>true<\/code>. Defaults to <code>true<\/code> when you don\u2019t call the method.<\/p>\n<pre><code>var io = require('socket.io')();\nio.on('connection', function(socket){\n  socket.compress(false).emit('an event', { some: 'data' });\n});\n<\/code><\/pre>\n<h3>Client<\/h3>\n<p>The <code>Client<\/code> class represents an incoming transport (engine.io) connection. A <code>Client<\/code> can be associated with many multiplexed <code>Socket<\/code> that belong to different <code>Namespace<\/code>s.<\/p>\n<h3>Client#conn<\/h3>\n<p>A reference to the underlying <code>engine.io<\/code> <code>Socket<\/code> connection.<\/p>\n<h3>Client#request<\/h3>\n<p>A getter proxy that returns the reference to the <code>request<\/code> that originated the engine.io connection. Useful for accessing request headers such as <code>Cookie<\/code> or <code>User-Agent<\/code>.<\/p>\n<h2>Debug \/ logging<\/h2>\n<p>Socket.IO is powered by debug. In order to see all the debug output, run your app with the environment variable <code>DEBUG<\/code> including the desired scope.<\/p>\n<p>To see the output from all of Socket.IO&#8217;s debugging scopes you can use:<\/p>\n<pre><code>DEBUG=socket.io* node myapp\n<\/code><\/pre>\n<h2>License<\/h2>\n<p>MIT<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How to use The following example attaches socket.io to a plain Node.JS HTTP server listening on port 3000. var server = require(&#8216;http&#8217;).createServer(); var io = require(&#8216;socket.io&#8217;)(server); io.on(&#8216;connection&#8217;, function(socket){ socket.on(&#8216;event&#8217;, function(data){}); socket.on(&#8216;disconnect&#8217;, function(){}); }); server.listen(3000); Standalone var io = require(&#8216;socket.io&#8217;)(); io.on(&#8216;connection&#8217;, function(socket){}); io.listen(3000); In conjunction with Express Starting with 3.0, express applications have become request handler [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-8086","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8086","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=8086"}],"version-history":[{"count":1,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8086\/revisions"}],"predecessor-version":[{"id":8637,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/8086\/revisions\/8637"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=8086"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=8086"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=8086"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}