Angular Websocket 在调用 send() 后立即关闭

Angular Websocket Closes Immediately after send() is called

下面包含我的 sendMessage() 函数,我在其中尝试 JSON.stringify() 一个对象,然后能够使用该 JSON 字符串调用 this.ws.send()。每当我尝试发送一个实际上只是一个字符串的字符串化对象时,我的 websocket 在 ws.send 被调用后立即关闭。另一方面,如果我只是向 ws.send() 提供我的消息内容(只是发送的短信),那么它就可以正常工作。

    ngOnInit() {
      this.messageForm = new FormGroup({
        message: new FormControl('')
      })
      this.routeSub = this.route.params.subscribe(params => {
        this.chatroomId = params['id']
        console.log(this.chatroomId)
      });
      this.store
      .pipe(
          select(getCurrUser)
      ).subscribe(data =>  {
          this.user = data
          this.userId = this.user.user_id || ""
          this.userType = this.user.user_category
          console.log(this.userId)
      })
      this.chatroomService.getChatroomsByUserId(this.userId).subscribe(data => {
        this.chatrooms = data

      })
      if (this.chatroomId) {
        this.chatroomService.getChatroomById(this.chatroomId).subscribe(chatroom => {
          this.currChatroom = chatroom
          this.user1 = chatroom.user1
          this.user2 = chatroom.user2
          this.user1_id = chatroom.user1_id
          this.user2_id = chatroom.user2_id
          if (this.user1_id == this.userId) {
            this.otherUser = this.user2
            this.otherUserId = this.user2_id
          } else {
            this.otherUser = this.user1
            this.otherUserId = this.user1_id
          }
        })
      }
      if (this.chatroomId) {
        this.chatroomService.getMessagesByChatroomId(this.chatroomId).subscribe(messages => {
          console.log(messages)
          this.messages = messages.reverse()
        })
        this.url = "ws://" + "localhost:8080" + "/api/" + this.chatroomId + "/ws";
        console.log(this.url)
        this.ws = new WebSocket(this.url)
        console.log(this.ws)
        this.ws.onopen = () => console.log('websocket connected!');
        this.ws.onmessage = (msg) => {
          const socket = msg.target as WebSocket;
          if (socket.url !== this.url) return socket.close();
          const d = JSON.parse(msg.data);
          console.log(d)
          this.messages = [...this.messages, d];
        }
        this.ws.onclose = () => console.log("websocket closed");
        window.addEventListener('beforeunload', () => this.ws.close())
      }
  }

    sendMessage() {
      const sender = this.user
      const id = this.userId
      const msg = this.messageForm.get('message').value
      var msgStr: string  = JSON.stringify({
        message: msg,
        sender_id: id,
        chatroom_id: this.chatroomId,
        sender: sender,
        timestamp: "Just now"
      })
      this.ws.send(msgStr)
      this.chatroomService.sendMessage(this.messageForm.get('message').value, this.userId, this.currChatroom.chatroom_id).subscribe(message => {
        console.log(message)
        this.messageForm.reset()
      })
    }

 





}

一旦 this.ws.send() 被调用,websocket 似乎就关闭了;但是,当我将 sendMessage 函数更改为只发送消息文本而不是 JSON 字符串时,它就可以工作了。因此,下面的代码块不会导致错误;但是,我需要传递其他数据,例如 sender_id.

sendMessage() {
      const sender = this.user
      const id = this.userId
      const msg = this.messageForm.get('message').value
      this.ws.send(msg)
      this.chatroomService.sendMessage(this.messageForm.get('message').value, this.userId,       this.currChatroom.chatroom_id).subscribe(message => {
        console.log(message)
        this.messageForm.reset()
      })
    }

问题是,在对我的 JSON 对象进行字符串化时,发件人属性是一个已定义的用户类型,无论出于何种原因,它都会导致问题,并且我的 Go 后端可能无法正确处理 API .

以下带有发件人的代码:发件人是罪魁祸首,因为发件人值是一个用户对象。

var msgStr: string  = JSON.stringify({
        message: msg,
        sender_id: id,
        chatroom_id: this.chatroomId,
        sender: sender,
        timestamp: "Just now"
      })

我通过简单地执行以下操作解决了这个问题:

var msgStr: string  = JSON.stringify({
        message: msg,
        sender: {
          first_name: sender.first_name,
          last_name: sender.last_name,
          user_id: sender.user_id
        },
        chatroom_id: this.chatroomId,
        timestamp: "Just now"
      })

我只向对象提供了来自我的发件人用户对象的必要数据,实际上只是名字、姓氏和 user_id。