# 2.1.5 在express中使用Socket.io

## Server(app.js)

```javascript
const app= require('express')()
const server = require('http').Server(app);
const io = require('socket.io')(server)

server.listen(80)
// 警告：app.listen(80)在这里没起作用，可能有端口被占用情况

app.get('/',(req,res)=>{
    res.sendFile(__dirname+'/index.html')
})

io.on('connection',(socket)=>{
    socket.emit('news',{hello:'world'}
    socket.on('my other event',(data)=>{
        console.log(data)
    })
})
```

## Client(index.html)

```markup
<script src="/socket.io/socket.io.js"></script>
<script>
    const socket= io.connect('http://localhost')
    socket.on('news',(data)=>{
        console.log(data)

        socket.emit('my other event',{my:'data'})
    })
</script>
```


---

# 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/2-wen-dang-docs/2.1-gai-lan/using_with_express.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.
