# ws-customer-service **Repository Path**: duans/ws-customer-service ## Basic Information - **Project Name**: ws-customer-service - **Description**: 基于websocket开发的"智能"客服 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-09-27 - **Last Updated**: 2024-09-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 就业复习-day02 ## 实现消息实时推送的解决方案 ### `http`短轮询 ![http短轮询](./media/http短轮询.png) ### `http`长轮询 ![http长轮询](./media/http长轮询.png) ### `WebSocket` ![websocket](./media/websocket.png) ![http轮询和websocket比较](./media/http轮询和websocket比较.png) ## `WebSocket` ### `WebSocket`和`http`协议的区别 - `http`是单项通信, 客户端主动发送请求, 服务端被动响应请求 - `websoket`可以实现双向通信, 只要客户端和服务端建立了通信通道, 服务端可以主动发送数据给客户端 ### 应用场景 1. 网页即时通信(网页聊天) 2. 移动`App`消息推送 3. 网页游戏 ## 原生方式实现`WebSocket` ### 客户端 ```jsx // 创建webscoket实例 const ws = new WebSocket('ws://localhost:8080'); // 监听会话通道是否打开 ws.onopen = function open() { console.log('WebSocket connected'); ws.send('Hello Server'); }; // 监听服务端消息 ws.onmessage = function(data) { console.log(data.data); }; // 监听websocket通道是否关闭 ws.onclose = function() { console.log('connect closed'); }; ``` ### 服务端 #### 安装websocket模块 ```jsx npm i ws ``` #### 创建websocket实例 ```jsx const WebSocket = require('ws'); // 创建websocket实例 const wss = new WebSocket.Server({ port: 8080 }); // 监听ws链接是否打开 wss.on('connection', function(ws) { // 监听客户端消息 ws.on('message', function(message) { console.log(message); }); // 向客户端发送消息 ws.send('something'); }); ``` ## 智能客服案例代码 ### 客户端代码 > index.html ```html Document

{{title}}

{{item.from}}:
``` ### 服务端代码 > index.js ```jsx const WebSocket = require('ws'); const http = require('http') // 创建websocket实例 const wss = new WebSocket.Server({ port: 8888 }); // 监听ws链接是否打开 wss.on('connection', function (ws) { // 监听客户端消息 ws.on('message', function (message) { const msg = message.toString() // console.log(message.toString(), '客户端来消息了'); http.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${msg}`, (response) => { let data = '' response.on('data', (chunk) => { data += chunk; }) response.on('end', () => { const res = JSON.parse(data) console.log(res.content, 'res'); // 将响应消息发送给客户端浏览器 ws.send(res.content) }) }) }); // 监听通信通道的关闭 ws.on('close', (e) => { console.log(e, 'close'); }) // 向客户端发送消息 // ws.send('something'); }); ``` # 参考文档 [vite打包兼容低版本浏览器的代码](https://vitejs.cn/vite5-cn/guide/using-plugins.html) [免费机器人接口](http://api.qingyunke.com/api.php?key=free&appid=0&msg=消息内容)