1"use strict";(self.webpackChunksample_website=self.webpackChunksample_website||[]).push([[3792],{3905:(e,t,n)=>{n.d(t,{Zo:()=>c,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 s(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 l(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 i=a.createContext({}),u=function(e){var t=a.useContext(i),n=t;return e&&(n="function"==typeof e?e(t):s(s({},t),e)),n},c=function(e){var t=u(e.components);return a.createElement(i.Provider,{value:t},e.children)},m="mdxType",p={inlineCode:"code",wrapper:function(e){var t=e.children;return a.createElement(a.Fragment,{},t)}},d=a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,o=e.originalType,i=e.parentName,c=l(e,["components","mdxType","originalType","parentName"]),m=u(n),d=r,h=m["".concat(i,".").concat(d)]||m[d]||p[d]||o;return n?a.createElement(h,s(s({ref:t},c),{},{components:n})):a.createElement(h,s({ref:t},c))}));function h(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var o=n.length,s=new Array(o);s[0]=d;var l={};for(var i in t)hasOwnProperty.call(t,i)&&(l[i]=t[i]);l.originalType=e,l[m]="string"==typeof e?e:r,s[1]=l;for(var u=2;u<o;u++)s[u]=n[u];return a.createElement.apply(null,s)}return a.createElement.apply(null,n)}d.displayName="MDXCreateElement"},5162:(e,t,n)=>{n.d(t,{Z:()=>s});var a=n(7294),r=n(4334);const o={tabItem:"tabItem_Ymn6"};function s(e){let{children:t,hidden:n,className:s}=e;return a.createElement("div",{role:"tabpanel",className:(0,r.Z)(o.tabItem,s),hidden:n},t)}},4866:(e,t,n)=>{n.d(t,{Z:()=>w});var a=n(3117),r=n(7294),o=n(4334),s=n(2466),l=n(6550),i=n(1980),u=n(7392),c=n(12);function m(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 p(e){const{values:t,children:n}=e;return(0,r.useMemo)((()=>{const e=t??m(n);return function(e){const t=(0,u.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 d(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,l.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,i._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 f(e){const{defaultValue:t,queryString:n=!1,groupId:a}=e,o=p(e),[s,l]=(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(!d({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}))),[i,u]=h({queryString:n,groupId:a}),[m,f]=function(e){let{groupId:t}=e;const n=function(e){return e?`docusaurus.tab.${e}`:null}(t),[a,o]=(0,c.Nk)(n);return[a,(0,r.useCallback)((e=>{n&&o.set(e)}),[n,o])]}({groupId:a}),g=(()=>{const e=i??m;return d({value:e,tabValues:o})?e:null})();(0,r.useLayoutEffect)((()=>{g&&l(g)}),[g]);return{selectedValue:s,selectValue:(0,r.useCallback)((e=>{if(!d({value:e,tabValues:o}))throw new Error(`Can't select invalid tab value=${e}`);l(e),u(e),f(e)}),[u,f,o]),tabValues:o}}var g=n(2389);const b={tabList:"tabList__CuJ",tabItem:"tabItem_LNqP"};function v(e){let{className:t,block:n,selectedValue:l,selectValue:i,tabValues:u}=e;const c=[],{blockElementScrollPositionUntilNextRender:m}=(0,s.o5)(),p=e=>{const t=e.currentTarget,n=c.indexOf(t),a=u[n].value;a!==l&&(m(t),i(a))},d=e=>{let t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":{const n=c.indexOf(e.currentTarget)+1;t=c[n]??c[0];break}case"ArrowLeft":{const n=c.indexOf(e.currentTarget)-1;t=c[n]??c[c.length-1];break}}t?.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,o.Z)("tabs",{"tabs--block":n},t)},u.map((e=>{let{value:t,label:n,attributes:s}=e;return r.createElement("li",(0,a.Z)({role:"tab",tabIndex:l===t?0:-1,"aria-selected":l===t,key:t,ref:e=>c.push(e),onKeyDown:d,onClick:p},s,{className:(0,o.Z)("tabs__item",b.tabItem,s?.className,{"tabs__item--active":l===t})}),n??t)})))}function k(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=f(e);return r.createElement("div",{className:(0,o.Z)("tabs-container",b.tabList)},r.createElement(v,(0,a.Z)({},e,t)),r.createElement(k,(0,a.Z)({},e,t)))}function w(e){const t=(0,g.Z)();return r.createElement(y,(0,a.Z)({key:String(t)},e))}},3120:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>h,frontMatter:()=>l,metadata:()=>u,toc:()=>m});var a=n(3117),r=(n(7294),n(3905)),o=n(4866),s=n(5162);const l={title:"Tutorial step #5 - Broadcasting",sidebar_label:"Step #5: Broadcasting",slug:"step-5"},i="Broadcasting",u={unversionedId:"tutorial/broadcasting",id:"tutorial/broadcasting",title:"Tutorial step #5 - Broadcasting",description:"The next goal is for us to emit the event from the server to the rest of the users.",source:"@site/docs/tutorial/06-broadcasting.md",sourceDirName:"tutorial",slug:"/tutorial/step-5",permalink:"/docs/v4/tutorial/step-5",draft:!1,editUrl:"https://github.com/socketio/socket.io-website/edit/main/docs/tutorial/06-broadcasting.md",tags:[],version:"current",lastUpdatedAt:1784117104,formattedLastUpdatedAt:"Jul 15, 2026",sidebarPosition:6,frontMatter:{title:"Tutorial step #5 - Broadcasting",sidebar_label:"Step #5: Broadcasting",slug:"step-5"},sidebar:"tutorialSidebar",previous:{title:"Step #4: Emitting events",permalink:"/docs/v4/tutorial/step-4"},next:{title:"Overview of the API",permalink:"/docs/v4/tutorial/api-overview"}},c={},m=[],p={toc:m},d="wrapper";function h(e){let{components:t,...n}=e;return(0,r.kt)(d,(0,a.Z)({},p,n,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("h1",{id:"broadcasting"},"Broadcasting"),(0,r.kt)("p",null,"The next goal is for us to emit the event from the server to the rest of the users."),(0,r.kt)("p",null,"In order to send an event to everyone, Socket.IO gives us the ",(0,r.kt)("inlineCode",{parentName:"p"},"io.emit()")," method."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"// this will emit the event to all connected sockets\nio.emit('hello', 'world'); \n")),(0,r.kt)("p",null,"If you want to send a message to everyone except for a certain emitting socket, we have the ",(0,r.kt)("inlineCode",{parentName:"p"},"broadcast")," flag for emitting from that socket:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"io.on('connection', (socket) => {\n socket.broadcast.emit('hi');\n});\n")),(0,r.kt)("p",null,"In this case, for the sake of simplicity we\u2019ll send the message to everyone, including the sender."),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},"io.on('connection', (socket) => {\n socket.on('chat message', (msg) => {\n io.emit('chat message', msg);\n });\n});\n")),(0,r.kt)("p",null,"And on the client side when we capture a ",(0,r.kt)("inlineCode",{parentName:"p"},"chat message")," event we\u2019ll include it in the page."),(0,r.kt)(o.Z,{groupId:"syntax",mdxType:"Tabs"},(0,r.kt)(s.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\n const form = document.getElementById('form');\n const input = document.getElementById('input');\n // highlight-start\n const messages = document.getElementById('messages');\n // highlight-end\n\n form.addEventListener('submit', (e) => {\n e.preventDefault();\n if (input.value) {\n socket.emit('chat message', input.value);\n input.value = '';\n }\n });\n\n // highlight-start\n socket.on('chat message', (msg) => {\n const item = document.createElement('li');\n item.textContent = msg;\n messages.appendChild(item);\n window.scrollTo(0, document.body.scrollHeight);\n });\n // highlight-end\n<\/script>\n"))),(0,r.kt)(s.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\n var form = document.getElementById('form');\n var input = document.getElementById('input');\n // highlight-start\n var messages = document.getElementById('messages');\n // highlight-end\n\n form.addEventListener('submit', function(e) {\n e.preventDefault();\n if (input.value) {\n socket.emit('chat message', input.value);\n input.value = '';\n }\n });\n\n // highlight-start\n socket.on('chat message', function(msg) {\n var item = document.createElement('li');\n item.textContent = msg;\n messages.appendChild(item);\n window.scrollTo(0, document.body.scrollHeight);\n });\n // highlight-end\n<\/script>\n")))),(0,r.kt)("p",null,"Let's see it in action:"),(0,r.kt)("video",{controls:!0,autoplay:"",loop:"",width:"100%"},(0,r.kt)("source",{src:"https://i.cloudup.com/transcoded/J4xwRU9DRn.mp4"})),(0,r.kt)("admonition",{type:"info"},(0,r.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,r.kt)(s.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/step5?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/step5?file=index.js"},"StackBlitz")))," "),(0,r.kt)(s.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/step5?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/step5?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.