# 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`长轮询  ### `WebSocket`   ## `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