import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
var stompClient = null;
// var customerId = ''; //客户Id
var info = {}; //所需参数信息
function connect(payload) { //建立连接
var socket = new SockJS('https://xxxxxx');
info = payload
stompClient = Stomp.over(socket); //获取STOMP子协议的客户端对象
if (stompClient) {
stompClient.connect({}, onConnected, onError); //向服务器发起websocket连接
}
}
function onConnected() { //ugid:用户组id
var quote = `{ugid: \"${info.fromUgid}\", type: \"${info.type}\", robotId: \"${info.robotId}\"}`;
stompClient.subscribe('/user/' + info.fromAccount + '/customerMessage', onMessageReceived); // 订阅服务端提供的某个topic
stompClient.send('/app/userChat.addUser', {},
JSON.stringify({ sender: info.fromAccount, content: quote, type: 'JOIN' })
)
}
function onError(error) {
console.log(error, '错误信息')
}
function sendMessage(event) { //发送消息
if (stompClient) {
//转换时间
let time = new Date().toLocaleDateString();
time = time.split('/');
time = time.join('-');
let b = new Date().toTimeString();
b = b.split(' ');
b = b[0];
time = `${time} ${b}`;
stompClient.send('/app/userChat.sendMessage', {},
// 需要的参数
JSON.stringify(
// `{'IsSeat':false,'msgType':901,'msgContent':{\"content\":\"${event}\",\"sendTime\":\"${time}\",\"receiverUserId\":\"2000\"},'msgId':'9ba19d69-4ea7-46b7-a0e1-a01811146e04','source':${info.fromDeviceId},'userId':${info.fromAccount}}`,
{
msgId: 'bb9ee191-e702-4952-b0f0-146df2151489',
source: info.fromDeviceId, //200代表H5
msgContent: `{\"content\":\"${event}\",\"sendTime\":\"${time}\",\"receiverUserId\":\"2000\"}`,
msgType: '901',
IsSeat: false,
userId: info.fromAccount,
}
));
}
}
function onMessageReceived(payload) {
console.log(payload, '存放的是服务端发送给我们的信息')
}
// // 断开连接
// function disconnect() {
// if (stompClient != null) {
// stompClient.disconnect();
// console.log("断开连接");
// }
// }
export default {
connect,
onConnected,
onError,
sendMessage,
// disconnect,
stompClient,
}
前端使用sockJs进行聊天通讯的功能
最新推荐文章于 2024-08-03 17:05:14 发布