前端使用sockJs进行聊天通讯的功能

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,



}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值