Aller au contenu principal
Version: 4.x


The next goal is for us to emit the event from the server to the rest of the users.

In order to send an event to everyone, Socket.IO gives us the io.emit() method.

// this will emit the event to all connected sockets
io.emit('hello', 'world');

If you want to send a message to everyone except for a certain emitting socket, we have the broadcast flag for emitting from that socket:

io.on('connection', (socket) => {

In this case, for the sake of simplicity we’ll send the message to everyone, including the sender.

io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);

And on the client side when we capture a chat message event we’ll include it in the page.

<script src="/"></script>
const socket = io();

const form = document.getElementById('form');
const input = document.getElementById('input');
const messages = document.getElementById('messages');

form.addEventListener('submit', (e) => {
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';

socket.on('chat message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
window.scrollTo(0, document.body.scrollHeight);

Let's see it in action:


You can run this example directly in your browser on: