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. server.listen(80)
  5. // 警告:app.listen(80)在这里没起作用,可能有端口被占用情况
  6. app.get('/',(req,res)=>{
  7. res.sendFile(__dirname+'/index.html')
  8. })
  9. io.on('connection',(socket)=>{
  10. socket.emit('news',{hello:'world'}
  11. socket.on('my other event',(data)=>{
  12. console.log(data)
  13. })
  14. })

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. socket.emit('my other event',{my:'data'})
  7. })
  8. </script>