# 使用socket.io实时通信
# 网络框架(服务端)
- 使用Nodejs网络框架express创建web服务
const http = require('http')
const express = require('express')
const app = express()
const server = http.createServer(app)//将app初始化为可以提供给Http服务器的函数处理程序
app.get('/', (req, res) => {//路由处理程序
res.send('<h1>Hello World!</h1>')
})
server.listen(3000, () => {
console.log('listening on *:3000');
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 客户端
- 重构路由处理程序,改用sendFile
app.get('/', (req, res) => {//路由处理程序
res.sendFile(__dirname + '/index.html')
})
1
2
3
2
3
# 集成Socket.io
- 一个socket包括:
- 一个服务器:集成或挂载在Node.JS HTTP服务器socket.io
- 一个客户端库:加载在浏览器端socket.io-client
- 在index.js中添加socket.io代码
const { Server } = require('socket.io')
const io = new Server(server)//通过server对象初始化一个socket.io实例
io.on('connection', (socket) => {//监听connection事件
console.log('a user connected');
})
1
2
3
4
5
2
3
4
5
- 在index.html中添加以下代码,加载socket.io-client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io()
</script>
1
2
3
4
2
3
4
- 启动服务端,每次刷新浏览器会在控制台打印'a user connected'
- 每个socket也会触发disconnect事件
io.on('connection', (socket) => {//监听connection事件
console.log('a user connected');
socket.on('disconnect',()=>{ //触发disconnect事件
console.log('user disconnected');
})
})
1
2
3
4
5
6
2
3
4
5
6
# 实现消息通信
# 客户端(socket.emit)->服务端(socket.on)
- index.html
<script> var socket = io(); var form = document.getElementById('form') var input = document.getElementById('input') form.addEventListener('submit', function (e) { e.preventDefault(); if (input.value) { socket.emit('chat message', input.value) input.value = '' } }) </script>
1
2
3
4
5
6
7
8
9
10
11
12 - index.js
io.on('connection', (socket) => {//监听connection事件 socket.on('chat message', (msg) => { console.log('message: ' + msg); }) })
1
2
3
4
5
# 服务端(io.emit)->客户端(socket.on)
- index.js
io.on('connection',(socket)=>{ socket.on('chat message',(msg)=>{ io.emit('chat message',msg) }) })
1
2
3
4
5 - index.html
socket.on('chat message', function (msg) { var item = document.createElement('li'); item.textContent = msg; messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight) })
1
2
3
4
5
6