💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# websocket聊天模板 [uniapp版本点击这里](WebSocket聊天.md) <br /> <br /> **vuex** store/modules/chat.js ```JavaScript import { Message } from 'element-ui' /** * 聊天 */ const state = { // 是否打开连接 isOpen: false, // websocket socket: null, // 心跳间隔 timeout: 10000, // 心跳事件 interval: null, // 重连次数 connectNum: 0, // ws token token: '', // 当前聊天场景 currentToUser: { id: 1, name: '', avatar: '', type: 's' // s=单聊, g群聊 }, // 我的信息 wsUserInfo: { addr: '', avatar: '', driver: '', fd: 0, id: 0, ip: '', nickName: '未登录', token: '' }, // 消息处理回调 wsCallback: null } const mutations = { /** * 关闭连接 */ wsClose(state) { if (state.isOpen) { state.isOpen = false state.socket.close() } }, /** * ws用户登录 * * @param {string} jwt jwtToken */ wsLogin(state, jwt) { this.dispatch('chat/SendRaw', { call: 'login.token', data: { token: jwt } }) }, /** * 设置ws收到消息回调 * * @param {function} callback */ set_message_callback(state, callback) { state.wsCallback = callback }, /** * 设置当前聊天对象 * * @param {object} payload {to:对方id, type:'类型, s=单聊/g=群聊'} */ set_chat_object(state, payload) { state.currentToUser.id = payload.id state.currentToUser.type = payload.type state.currentToUser.name = '' state.currentToUser.avatar = '' // 查询用户信息 this.dispatch('chat/SendRaw', { call: 'user.get', data: { uid: payload.id } }) } } const actions = { /** * 初始化 or 连接websocket */ initWs({ commit, state, rootState }) { const that = this console.log('检查是否已链接') if (state.isOpen) return // 防止重复连接 // 连接ws const wsurl = process.env.VUE_APP_WEB_SOCKET state.socket = new WebSocket(wsurl) if (!state.socket) return // 连接失败 // 事件_连接成功 state.socket.onopen = () => { console.log('ws连接成功') // 将连接状态设为已连接 state.isOpen = true // 心跳定时器 state.interval = setInterval(() => { // 发送心跳 if (state.isOpen) { try { state.socket.send('ping') } catch (err) { console.log('心跳发送失败了 ...执行重连', err) Message({ msg: '正在尝试重新连接' + (state.connectNum + 1) + '次', type: 'error', duration: 2 * 1000 }) state.isOpen = false that.dispatch('chat/reConnect') } } }, state.timeout) } // 事件_收到消息 state.socket.onmessage = (e) => { // 服务器响应心跳 if (e.data === 'pong') { return } // 解析包 const pack = JSON.parse(e.data) if (typeof pack !== 'object') { return } // 包拦截处理 switch (pack.call) { case 'login.token': // 登录 state.token = pack.result.token state.wsUserInfo = pack.result break case 'chat.recv': // 收到信息 // TODO: 播放提示音 break case 'user.get': // 用户信息获取 // 更新聊天对象的用户信息 if (pack.result.id == state.currentToUser.id) { state.currentToUser.name = pack.result.nickName state.currentToUser.avatar = pack.result.avatar } break } // 转向回调处理 if (typeof state.wsCallback == 'function') { state.wsCallback(pack) } } // 事件_连接关闭 state.socket.onclose = () => { state.isOpen = false state.socket = null // 清除定时器 clearTimeout(state.interval) state.interval = null } // 事件_连接错误 state.socket.onerror = (e) => { state.isOpen = false state.socket = null } }, /** * 重连 */ reConnect({ commit, state }) { // 逐渐延长重连时间 var time = 3000; if (state.connectNum < 20) { time = 3000; } else if (state._connectNum < 50) { time = 10000; } else { time = 450000; } state.timer = setTimeout(() => { this.dispatch('chat/initWs') }, time) state.connectNum += 1 }, /** * 发送消息 * * @param {object} payload 消息数据 * * payload格式: * {type:消息类型, msg:消息数据} */ SendMsg({ commit, state }, payload) { var data = { to: payload.to, origin: state.currentToUser.type, type: payload.type, msg: payload.msg } this.dispatch('chat/SendRaw', { call: 'chat.send', data: data }) }, /** * 发送数据 * * @param {object} data * * data格式: * { call:"请求标识", data:{...其他数据...} } */ SendRaw({ commit, state }, data) { try { const message = { call: data.call, body: data.data, token: state.token } const msgText = JSON.stringify(message) console.log(typeof state.socket) if (state.socket && state.isOpen) { state.socket.send(msgText) } } catch (err) { console.log(err) } } } export default { namespaced: true, state, mutations, actions } ``` **使用** 在vuex里引入模块 ```JavaScript const store = new Vuex.Store({ modules: { chat // chat }, getters }) ``` 连接 (main.js) ```javascript // 连接websocket store.dispatch('chat/initWs') ``` 登录 ```JavaScript store.commit('chat/wsLogin', state.token) // 在用户登录后, 同步登录ws ```