Skip to main content
Version: 4.x

广播

¥Broadcasting

我们的下一个目标是将事件从服务器发送给其他用户。

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

为了向所有人发送事件,Socket.IO 给我们提供了 io.emit() 方法。

¥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');

如果你想向除某个发送套接字之外的所有人发送消息,我们有 broadcast 标志用于从该套接字发送:

¥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) => {
socket.broadcast.emit('hi');
});

在这种情况下,为了简单起见,我们会将消息发送给每个人,包括发送者。

¥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);
});
});

在客户端,当我们捕获 chat message 事件时,我们会将其包含在页面中。

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

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

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

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

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

让我们看看它的实际效果:

¥Let's see it in action:

https://i.cloudup.com/transcoded/J4xwRU9DRn.mp4

info

你可以直接在浏览器中运行此示例:

¥You can run this example directly in your browser on: