# 2.1.4 在Node HTTP 服务中使用

## Server(app)，服务端

```javascript
const app = require('http').createServer(handler)
const io = require('socket.io')(app)
const fs = require('fs')

app.listen(80)

function handler(req,res){
    fs.readFile(__dirname+'/index.html',(err,data)=>{
        if(err){
            res.writeHead(500);
            return res.end('Error loading index.html,server error!')
        }
        res.writeHead(200);
        res.end(data)
    }),
}

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('http://localhost');//这里一定要http开头，因为socket.io不是websocket实现的
    socket.on('news',(data)=>{
        console.log(data)//收到服务器emit的消息
        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_node_http_server.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.
