Search…
2.1.5 在express中使用Socket.io

Server(app.js)

1
const app= require('express')()
2
const server = require('http').Server(app);
3
const io = require('socket.io')(server)
4
5
server.listen(80)
6
// 警告:app.listen(80)在这里没起作用,可能有端口被占用情况
7
8
app.get('/',(req,res)=>{
9
res.sendFile(__dirname+'/index.html')
10
})
11
12
io.on('connection',(socket)=>{
13
socket.emit('news',{hello:'world'}
14
socket.on('my other event',(data)=>{
15
console.log(data)
16
})
17
})
Copied!

Client(index.html)

1
<script src="/socket.io/socket.io.js"></script>
2
<script>
3
const socket= io.connect('http://localhost')
4
socket.on('news',(data)=>{
5
console.log(data)
6
7
socket.emit('my other event',{my:'data'})
8
})
9
</script>
Copied!