为什么我在websocket中发送的每条消息之后都收到多条消息

时间:2019-10-18 00:03:38

标签: javascript websocket chat

我正在尝试创建一个聊天应用程序,如果我使用我的应用程序通过websocket发送了两条消息,那么我将收到每个发送消息的人的2条消息。如果我再发送一条消息,那么我将收到每个向我发送消息的人的三则消息。


chat () {
    const sendMsgDiv = this.shadowRoot.querySelector('.sendMessage')
    sendMsgDiv.classList.remove('removed')
    const submit = this.shadowRoot.querySelector('#submit')
    const input = this.shadowRoot.querySelector('#write')
    input.innerHTML = ''
    input.setAttribute('placeholder', 'Write a message...')
    submit.addEventListener('click', event => {
      event.stopPropagation()
      this.sendMessage(input.value)
      input.value = ''
    })
  }

sendMessage (message) {
    const data = {
      type: 'message',
      data: message,
      username: window.localStorage.getItem('username'),
      channel: 'mychannel'
    }
    const socket = new window.WebSocket('<server_name>', 'mychannel')
    // show the sender message
    socket.onopen = event => {
      socket.send(JSON.stringify(data))
      const message = document.createElement('p')
      message.setAttribute('class', 'senderMessage')
      message.innerHTML = data.username + ' : ' + data.data
      this.shadowRoot.querySelector('.messages').appendChild(message)
    }
    // check if the reciever message is from the same user that sent it
    socket.addEventListener('message', event => {
      const message = JSON.parse(event.data)
      console.log(message)
      if (message.username !== window.localStorage.getItem('username') && message.username !== 'The Server') {
        console.log('message arrived')
        const recieverMessage = document.createElement('p')
        recieverMessage.setAttribute('class', 'recieverMessage')
        recieverMessage.innerHTML = message.username + ' : ' + message.data
        this.shadowRoot.querySelector('.messages').appendChild(recieverMessage)
      }
    })
  }

0 个答案:

没有答案