> For the complete documentation index, see [llms.txt](https://socket.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://socket.gitbook.io/docs/2-wen-dang-docs/2.1-gai-lan/using_with_node_http_server.md).

# 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>
```
