与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),客户端
<script src="/socket.io/socket.io.js"></script>
<script>
const socket=io('http://localhost');
socket.on('news',(data)=>{
console.log(data)
socket.emit('my other event',{my:'data'})
})
</script>