Taro项目使用websocket实现一个在线聊天室

Taro提供了一些websocket相关的接口

https://taro-docs.jd.com/taro/docs/apis/network/webSocket/connectSocket

1、聊天室的效果

Taro项目使用websocket实现一个在线聊天室_第1张图片

 

二、实现思路

1、Taro.connectSocket创建连接

2、onMessage监听服务器返回的数据

3、创建一个全局存储消息的数组   let arr = []

4、Input输入框获取到的值,在点击发送的时候,放进arr数组,arr.push({ nickname: 'Merryaa' , message: '来了阿伟', flag: false }),flag是自己添加的标识符,自己的消息为true, 服务器返回的消息为false

5、使用sendSocketMessage发送消息

Taro.sendSocketMessage({

        data: Inputvalue

      })

6、在render里面遍历数组展示消息,flag: false 、true标识是为了写样式判断左右消息显示

三、具体实现

1、建立连接

//全局变量
let socketOpen = false;
let socketMsgQueue = [
  { nickname: 'Merryaa' , message: '来了阿伟', flag: false }
];


componentDidShow () {

    this.fetchInitData();
    this.getwebsocket();
  
  }

  // 建立连接
  getwebsocket = () => {
    const { teamplayRoomId } = this.$router.params;
    const { Inputvalue } = this.state;
    const token = cache.get('token');
    const nickname = cache.get('nickname');
    Taro.connectSocket({
      url: `wss://xxxxxxxxx/ws/chatRoom?chatRoomId=${teamplayRoomId}&token=${token}&nickname=${nickname}`,
      header:{
        'content-type': 'application/json'
      },
      success: function () {
        console.log('connect success')
      }
    }).then(task => {
      task.onOpen(function () {
        socketOpen = true;
        for (let i = 0; i < socketMsgQueue.length; i++){
          task.send({ data: socketMsgQueue[i].message }).then(res => {
            // console.warn('send sendsend', res)

          })
        }
        // socketMsgQueue = []
        console.warn('onOpen')
        console.warn('task', task)
        

      })
      task.onMessage(function (msg) {
        // 监听服务器返回的消息,并放在数组里面
        console.log('收到服务器内容 msg:' + msg)
        const setInfo = JSON.parse(msg);
        // {"nickname":"server","message":"broadcast"}
        if (setInfo && nickname.nickname !== "server") {
          socketMsgQueue.push({ ...setInfo, flag: false })
        }
       

        task.close();
      })
      task.onError(function () {
        console.warn('onError')
        socketOpen = false;

        this.reconnect();
      })
      task.onClose(function (e) {
        console.warn('onClose: ', e)
        socketOpen = false;

        this.reconnect();
      })
    })
  }

断开重连


  // 断开重连
  reconnect = () => {
    if (socketOpen) return;
    socketOpen = true;
    setTimeout(function () {
      this.getwebsocket();
    }, 2000)
  }

2、获取消息,保存到数组,然后发送

 handleChangeInput = (value) => {
   
    console.warn('Inputvalue', value)
    this.setState({
      Inputvalue: value
    })

    return;
  }

  sendMessage = () => {
    const { Inputvalue } = this.state;
    const nickname = cache.get('nickname');
    socketMsgQueue.push({ nickname: nickname , message: Inputvalue, flag: true });
    console.warn("sendMessage Inputvalue", Inputvalue)
    if (socketOpen) {
      Taro.sendSocketMessage({
        data: Inputvalue
      }).then(res => {
        console.warn('sendMessage sendsend', res)
       if (res.errMsg === "sendSocketMessage:ok" ) {
        hasSend = true;
       }
      })
    }

三、渲染数组的消息

renderSendMsg = () => {
    const { Inputvalue } = this.state;
    return(
      
        

        
        {/* 

         */}
        
          发送
        
      
    )
  }

样式:

.chat{
     
    &-box{
        margin-bottom: 30px;
        padding: 30px 45px;
        height: 350px;
        background-color: #28427d;
        border-radius: 10px;
        overflow: scroll;
         &-item {
            height: 60px;
            width: auto;
            margin-bottom: 22px;
             &-me-message {
                 display: inline-block;
                 height: 60px;
                 width: auto !important;
                 min-width: 60px !important;
                 background-color: seagreen;
                 color: black;
                 text-align: right;
                 margin-bottom: 10px;
                 border-radius: 10px;
                 font-family: PingFang-SC-Regular;
                 font-size: 25px;
                 float: right;

                 padding-top: 10px;
                 padding-right: 15px;
                 padding-left: 15px;
             }
     
             &-qunfa-message {
                 display: inline-block;
                 height: 60px;
                 min-width: 60px;
                 width: auto;
                 background-color:grey;
                 color: whitesmoke;
                 text-align: left;
                 margin-bottom: 10px;
                 border-radius: 10px;
                 font-family: PingFang-SC-Regular;
                 font-size: 25px;
                 padding-top: 10px;
                 padding-left: 15px;
                 padding-right: 15px;
                 
             }
         }
    }

}

 

你可能感兴趣的:(websocket,Taro,前端,Taro,小程序,websocket,聊天室)