2.1.4 在Node HTTP 服务中使用

Server(app),服务端

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),客户端

Last updated

Was this helpful?