# 1-6 广播(Broadcasting)

下一个目标是让我们从服务器向其他用户发送事件

为了发送一个事件给所有人，`socket.io`给我们提供了`io.emit`:

```javascript
io.emit('some event',{for:'hey gay! to everyone'})
```

如果你想向除了某些`socket`以外的所有人发送消息，我们有`broadcasting`广播标志：

```javascript
// 向所有非自己连接的客户端，发送连接数
io.on('connection',(socket)=>{
    socket.broadcast.emit('hi')
})
```

如图，刷新中间的窗口，服务器则向左右两侧的窗口推送消息：

![广播](/files/-L_vv0zayTW6Tq5TJtrK)

在这种情况下。为了简单起见，我们会将消息发送给所有人，包括发件人

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

在客户端，我们捕获到聊天消息，将其也包含在页面中，现在客户端的JS代码如下：

```javascript
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>
```

这就是完成了我们的聊天应用程序，大约20行代码！它就是这样子：

> mp4 ：<https://i.cloudup.com/transcoded/J4xwRU9DRn.mp4>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://socket.gitbook.io/docs/1-zhi-nan-guide/broadcasting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
