PageSourceSearch

https://socket.io/assets/js/87a9bcb7.95881784.js

js socket.io collected 2026-09-24 07:24:04 UTC 16,027 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunksample_website=self.webpackChunksample_website||[]).push([[1341],{3905:(e,t,n)=>{n.d(t,{Zo:()=>u,kt:()=>h});var a=n(7294);function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t){if(null==e)return{};var n,a,r=function(e,t){if(null==e)return{};var n,a,r={},o=Object.keys(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)>=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}var l=a.createContext({}),c=function(e){var t=a.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):i(i({},t),e)),n},u=function(e){var t=c(e.components);return a.createElement(l.Provider,{value:t},e.children)},p="mdxType",d={inlineCode:"code",wrapper:function(e){var t=e.children;return a.createElement(a.Fragment,{},t)}},m=a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,o=e.originalType,l=e.parentName,u=s(e,["components","mdxType","originalType","parentName"]),p=c(n),m=r,h=p["".concat(l,".").concat(m)]||p[m]||d[m]||o;return n?a.createElement(h,i(i({ref:t},u),{},{components:n})):a.createElement(h,i({ref:t},u))}));function h(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var o=n.length,i=new Array(o);i[0]=m;var s={};for(var l in t)hasOwnProperty.call(t,l)&&(s[l]=t[l]);s.originalType=e,s[p]="string"==typeof e?e:r,i[1]=s;for(var c=2;c<o;c++)i[c]=n[c];return a.createElement.apply(null,i)}return a.createElement.apply(null,n)}m.displayName="MDXCreateElement"},5162:(e,t,n)=>{n.d(t,{Z:()=>i});var a=n(7294),r=n(4334);const o={tabItem:"tabItem_Ymn6"};function i(e){let{children:t,hidden:n,className:i}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,i),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>N});var a=n(3117),r=n(7294),o=n(4334),i=n(2466),s=n(6550),l=n(1980),c=n(7392),u=n(12);function p(e){return function(e){return r.Children.map(e,(e=>{if(!e||(0,r.isValidElement)(e)&&function(e){const{props:t}=e;return!!t&&"object"==typeof t&&"value"in t}(e))return e;throw new Error(`Docusaurus error: Bad <Tabs> child <${"string"==typeof e.type?e.type:e.type.name}>: all children of the <Tabs> component should be <TabItem>, and every <TabItem> should have a unique "value" prop.`)}))?.filter(Boolean)??[]}(e).map((e=>{let{props:{value:t,label:n,attributes:a,default:r}}=e;return{value:t,label:n,attributes:a,default:r}}))}function d(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??p(n);return function(e){const t=(0,c.l)(e,((e,t)=>e.value===t.value));if(t.length>0)throw new Error(`Docusaurus error: Duplicate values "${t.map((e=>e.value)).join(", ")}" found in <Tabs>. Every value needs to be unique.`)}(e),e}),[t,n])}function m(e){let{value:t,tabValues:n}=e;return n.some((e=>e.value===t))}function h(e){let{queryString:t=!1,groupId:n}=e;const a=(0,s.k6)(),o=function(e){let{queryString:t=!1,groupId:n}=e;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The <Tabs> component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return n??null}({queryString:t,groupId:n});return[(0,l._X)(o),(0,r.useCallback)((e=>{if(!o)return;const t=new URLSearchParams(a.location.search);t.set(o,e),a.replace({...a.location,search:t.toString()})}),[o,a])]}function g(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=d(e),[i,s]=(0,r.useState)((()=>function(e){let{defaultValue:t,tabValues:n}=e;if(0===n.length)throw new Error("Docusaurus error: the <Tabs> component requires at least one <TabItem> children component");if(t){if(!m({value:t,tabValues:n}))throw new Error(`Docusaurus error: The <Tabs> has a defaultValue "${t}" but none of its children has the corresponding value. Available values are: ${n.map((e=>e.value)).join(", ")}. If you intend to show no default tab, use defaultValue={null} instead.`);return t}const a=n.find((e=>e.default))??n[0];if(!a)throw new Error("Unexpected error: 0 tabValues");return a.value}({defaultValue:t,tabValues:o}))),[l,c]=h({queryString:n,groupId:a}),[p,g]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,u.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),k=(()=>{const e=l??p;return m({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{k&&s(k)}),[k]);return{selectedValue:i,selectValue:(0,r.useCallback)((e=>{if(!m({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);s(e),c(e),g(e)}),[c,g,o]),tabValues:o}}var k=n(2389);const f={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function b(e){let{className:t,block:n,selectedValue:s,selectValue:l,tabValues:c}=e;const u=[],{blockElementScrollPositionUntilNextRender:p}=(0,i.o5)(),d=e=>{const t=e.currentTarget,n=u.indexOf(t),a=c[n].value;a!==s&&(p(t),l(a))},m=e=>{let t=null;switch(e.key){case"Enter":d(e);break;case"ArrowRight":{const n=u.indexOf(e.currentTarget)+1;t=u[n]??u[0];break}case"ArrowLeft":{const n=u.indexOf(e.currentTarget)-1;t=u[n]??u[u.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},c.map((e=>{let{value:t,label:n,attributes:i}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:s===t?0:-1,"aria-selected":s===t,key:t,ref:e=>u.push(e),onKeyDown:m,onClick:d},i,{className:(0,o.Z)("tabs__item",f.tabItem,i?.className,{"tabs__item--active":s===t})}),n??t)})))}function v(e){let{lazy:t,children:n,selectedValue:a}=e;
1const o=(Array.isArray(n)?n:[n]).filter(Boolean);if(t){const e=o.find((e=>e.props.value===a));return e?(0,r.cloneElement)(e,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},o.map(((e,t)=>(0,r.cloneElement)(e,{key:t,hidden:e.props.value!==a}))))}function y(e){const t=g(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",f.tabList)},r.createElement(b,(0,a.Z)({},e,t)),r.createElement(v,(0,a.Z)({},e,t)))}function N(e){const t=(0,k.Z)();return r.createElement(y,(0,a.Z)({key:String(t)},e))}},9809:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>u,contentTitle:()=>l,default:()=>h,frontMatter:()=>s,metadata:()=>c,toc:()=>p});var a=n(3117),r=(n(7294),n(3905)),o=n(4866),i=n(5162);const s={title:"Tutorial step #3 - Integrating Socket.IO",sidebar_label:"Step #3: Integrating Socket.IO",slug:"step-3"},l="Integrating Socket.IO",c={unversionedId:"tutorial/integrating-socket-io",id:"tutorial/integrating-socket-io",title:"Tutorial step #3 - Integrating Socket.IO",description:"Socket.IO is composed of two parts:",source:"@site/docs/tutorial/04-integrating-socket-io.md",sourceDirName:"tutorial",slug:"/tutorial/step-3",permalink:"/docs/v4/tutorial/step-3",draft:!1,editUrl:"https://github.com/socketio/socket.io-website/edit/main/docs/tutorial/04-integrating-socket-io.md",tags:[],version:"current",lastUpdatedAt:1784117104,formattedLastUpdatedAt:"Jul 15, 2026",sidebarPosition:4,frontMatter:{title:"Tutorial step #3 - Integrating Socket.IO",sidebar_label:"Step #3: Integrating Socket.IO",slug:"step-3"},sidebar:"tutorialSidebar",previous:{title:"Step #2: Serving HTML",permalink:"/docs/v4/tutorial/step-2"},next:{title:"Step #4: Emitting events",permalink:"/docs/v4/tutorial/step-4"}},u={},p=[],d={toc:p},m="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(m,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h1",{id:"integrating-socketio"},"Integrating Socket.IO"),(0,r.kt)("p",null,"Socket.IO is composed of two parts:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"A server that integrates with (or mounts on) the Node.JS HTTP Server (the ",(0,r.kt)("a",{parentName:"li",href:"https://www.npmjs.com/package/socket.io"},(0,r.kt)("inlineCode",{parentName:"a"},"socket.io"))," package)"),(0,r.kt)("li",{parentName:"ul"},"A client library that loads on the browser side (the ",(0,r.kt)("a",{parentName:"li",href:"https://www.npmjs.com/package/socket.io-client"},(0,r.kt)("inlineCode",{parentName:"a"},"socket.io-client"))," package)")),(0,r.kt)("p",null,"During development, ",(0,r.kt)("inlineCode",{parentName:"p"},"socket.io")," serves the client automatically for us, as we\u2019ll see, so for now we only have to install one module:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},"npm install socket.io\n")),(0,r.kt)("p",null,"That will install the module and add the dependency to ",(0,r.kt)("inlineCode",{parentName:"p"},"package.json"),". Now let\u2019s edit ",(0,r.kt)("inlineCode",{parentName:"p"},"index.js")," to add it:"),(0,r.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"cjs",label:"CommonJS",default:!0,mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"const express = require('express');\nconst { createServer } = require('node:http');\nconst { join } = require('node:path');\n// highlight-start\nconst { Server } = require('socket.io');\n// highlight-end\n\nconst app = express();\nconst server = createServer(app);\n// highlight-start\nconst io = new Server(server);\n// highlight-end\n\napp.get('/', (req, res) => {\n  res.sendFile(join(__dirname, 'index.html'));\n});\n\n// highlight-start\nio.on('connection', (socket) => {\n  console.log('a user connected');\n});\n// highlight-end\n\nserver.listen(3000, () => {\n  console.log('server running at http://localhost:3000');\n});\n"))),(0,r.kt)(i.Z,{value:"mjs",label:"ES modules",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"import express from 'express';\nimport { createServer } from 'node:http';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n// highlight-start\nimport { Server } from 'socket.io';\n// highlight-end\n\nconst app = express();\nconst server = createServer(app);\n// highlight-start\nconst io = new Server(server);\n// highlight-end\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\napp.get('/', (req, res) => {\n  res.sendFile(join(__dirname, 'index.html'));\n});\n\n// highlight-start\nio.on('connection', (socket) => {\n  console.log('a user connected');\n});\n// highlight-end\n\nserver.listen(3000, () => {\n  console.log('server running at http://localhost:3000');\n});\n")))),(0,r.kt)("p",null,"Notice that I initialize a new instance of ",(0,r.kt)("inlineCode",{parentName:"p"},"socket.io")," by passing the ",(0,r.kt)("inlineCode",{parentName:"p"},"server")," (the HTTP server) object. Then I listen on the ",(0,r.kt)("inlineCode",{parentName:"p"},"connection")," event for incoming sockets and log it to the console."),(0,r.kt)("p",null,"Now in index.html add the following snippet before the ",(0,r.kt)("inlineCode",{parentName:"p"},"</body>")," (end body tag):"),(0,r.kt)(o.Z,{groupId:"syntax",mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"es6",label:"ES6",default:!0,mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-html"},'<script src="/socket.io/socket.io.js"><\/script>\n<script>\n  const socket = io();\n<\/script>\n'))),(0,r.kt)(i.Z,{value:"es5",label:"ES5",mdxType:"TabItem"},(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-html"},'<script src="/socket.io/socket.io.js"><\/script>\n<script>\n  var socket = io();\n<\/script>\n')))),(0,r.kt)("p",null,"That\u2019s all it takes to load the ",(0,r.kt)("inlineCode",{parentName:"p"},"socket.io-client"),", which exposes an ",(0,r.kt)("inlineCode",{parentName:"p"},"io")," global (and the endpoint ",(0,r.kt)("inlineCode",{parentName:"p"},"GET /socket.io/socket.io.js"),"), and then connect."),(0,r.kt)("p",null,"If you would like to use the local version of the client-side JS file, you can find it at ",(0,r.kt)("inlineCode",{parentName:"p"},"node_modules/socket.io/client-dist/socket.io.js"),"."),(0,r.kt)("admonition",{type:"tip"},(0,r.kt)("p",{parentName:"admonition"},"You can also use a CDN instead of the local files (e.g. ",(0,r.kt)("inlineCode",{parentName:"p"},'<script src="https://cdn.socket.io/4.8.3/socket.io.min.js"><\/script>'),").")),(0,r.kt)("p",null,"Notice that I\u2019m not specifying any URL when I call ",(0,r.kt)("inlineCode",{parentName:"p"},"io()"),", since it defaults to trying to connect to the host that serves the page."),(0,r.kt)("admonition",{type:"note"},(0,r.kt)("p",{parentName:"admonition"},"If you're behind a reverse proxy such as apache or nginx please take a look at ",(0,r.kt)("a",{parentName:"p",href:"/docs/v4/reverse-proxy/"},"the documentation for it"),"."),(0,r.kt)("p",{parentName:"admonition"},"If you're hosting your app in a folder that is ",(0,r.kt)("em",{parentName:"p"},"not")," the root of your website (e.g., ",(0,r.kt)("inlineCode",{parentName:"p"},"https://example.com/chatapp"),") then you also need to specify the ",(0,r.kt)("a",{parentName:"p",href:"/docs/v4/server-options/#path"},"path")," in both the server and the client.")),(0,r.kt)("p",null,"If you now restart the process (by hitting Control+C and running ",(0,r.kt)("inlineCode",{parentName:"p"},"node index.js")," again) and then refresh the webpage you should see the console print \u201ca user connected\u201d."),(0,r.kt)("p",null,"Try opening several tabs, and you\u2019ll see several messages."),(0,r.kt)("img",{src:"/images/chat-4.png",alt:"A console displaying several messages, indicating that some users have connected"}),(0,r.kt)("p",null,"Each socket also fires a special ",(0,r.kt)("inlineCode",{parentName:"p"},"disconnect")," event:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"io.on('connection', (socket) => {\n  console.log('a user connected');\n  socket.on('disconnect', () => {\n    console.log('user disconnected');\n  });\n});\n")),(0,r.kt)("p",null,"Then if you refresh a tab several times you can see it in action."),(0,r.kt)("img",{src:"/images/chat-5.png",alt:"A console displaying several messages, indicating that some users have connected and disconnected"}),(0,r.kt)("admonition",{type:"info"},(0,r.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,r.kt)(i.Z,{value:"cjs",label:"CommonJS",default:!0,attributes:{className:"display-none"},mdxType:"TabItem"},(0,r.kt)("p",{parentName:"admonition"},"You can run this example directly in your browser on:"),(0,r.kt)("ul",{parentName:"admonition"},(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://codesandbox.io/p/sandbox/github/socketio/chat-example/tree/cjs/step3?file=index.js"},"CodeSandbox")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://stackblitz.com/github/socketio/chat-example/tree/cjs/step3?file=index.js"},"StackBlitz"))),"  "),(0,r.kt)(i.Z,{value:"mjs",label:"ES modules",attributes:{className:"display-none"},mdxType:"TabItem"},(0,r.kt)("p",{parentName:"admonition"},"You can run this example directly in your browser on:"),(0,r.kt)("ul",{parentName:"admonition"},(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://codesandbox.io/p/sandbox/github/socketio/chat-example/tree/esm/step3?file=index.js"},"CodeSandbox")),(0,r.kt)("li",{parentName:"ul"},(0,r.kt)("a",{parentName:"li",href:"https://stackblitz.com/github/socketio/chat-example/tree/esm/step3?file=index.js"},"StackBlitz"))),"  "))))}h.isMDXComponent=!0}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.