数据的实时性
轮询
- 没隔多长时间发起一次请求 也叫短连接
- 客户端主动发起请求,服务端响应信息
长连接
-
服务器端主动推送信息
站内信 主动弹出聊天框之类的通讯软件
-
抽奖
长连接的实现方式
node 中的内置模块 net (不常用)
-
h5新增的特性 websocket
- 有兼容性问题
- 低版本浏览器不支持
- 使用方便
- 通过message接收信息
- 通过send 发送信息
- 有兼容性问题
-
socket.io库
- 第三方库,需要引入文件
- 没有兼容性问题,
- 使用麻烦一点
- on 自己定事件
- emit 触发事件
-
任何一个长连接 由两部分组成 客户端 服务端
服务端
-
websocket
安装模块
-
引入模块 创建长连接的服务器
const WebSocket = require('ws') const ws = new WebSocket.Server({port:8080}) ws.on('connection',(client)=>{ //client 客户端的连接对象 console.log('客户端连接了') client.send('你好') //client对象通过send方法来向客户端传递消息 client.on('message',(msg)=>{//接收来自客户端的消息 console.log('来自客户端的消息',msg) }) client.on('close',()=>{ console.log('客户端主动断开连接')//客户端页面关闭 }) })
- 一个服务端连接多个客户端可以建立个clinets数组来保存所有的clinet对象
- D:\Learn\千峰\课堂笔记\课堂笔记\第三阶段\NZ-1911\node\node08
- 一个服务端连接多个客户端可以建立个clinets数组来保存所有的clinet对象
-
socket.io
创建socket服务端
等待客户端连接
emit(触发客户端定义的事件,参数)等待被客户端触发的事件,传递给客户端的数据
on (‘自定义事件’,()=>{})接收客户端的数据
安装模块
-
引入模块,建立长连接服务器
var express = require('express') var app = express() // 将socket服务器 和express 绑定到一起 var server = require('http').Server(app); var io = require('socket.io')(server); io.on('connection',(client)=>{ console.log('客户端连接') // 触发客户端的自定义事件 hehe 参数是123 client.emit('hehe',123) // 服务端创建一个叫xixi的自定义事件监听 等待前端触发 client.on('xixi',(data)=>{ console.log('来自客户端的消息',data) }) }) server.listen(8081,()=>{ console.log('server start') });
- soket.io可以和express可以同时监视一个端口
-
客户端
-
websocket
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="text" id="msg"> <button onclick="sendMsg()">发送消息</button> <script> let ws = new WebSocket('ws://localhost:8080')//websocket是es5新增对象,直接可以使用 ws.onopen=()=>{ //通过onopen方法来监听服务器 console.log('服务端连接') } ws.onmessage=(msg)=>{ //通过onmessage方法来接收服务端传过来的信息。 console.log("接收服务端的消息",msg) } ws.onclose = (msg)=>{//如果服务器端断开连接监听 console.log('服务器端断开连接') } function sendMsg(){ let msg = document.getElementById('msg').value; ws.send(msg)//客户端向服务端发送消息 } </html>
-
-
socket.io
连接服务器
通过on(‘自定义事件’)接收服务端的消息
通过emit 触发服务端的事件发送消息
-
需要找一个文件,socket.io.js
- node_modules/socket-client/dist/在这找
var express = require('express') var app = express() // 将socket服务器 和express 绑定到一起 var server = require('http').Server(app); var io = require('socket.io')(server); io.on('connection',(client)=>{ console.log('客户端连接') // 触发客户端的自定义事件 hehe 参数是123 client.emit('hehe',123) // 服务端创建一个叫xixi的自定义事件监听 等待前端触发 client.on('xixi',(data)=>{ console.log('来自客户端的消息',data) }) }) server.listen(8081,()=>{ console.log('server start') });