【问题标题】:Cannot send data if the connection is not in the 'Connected' State | SignalR, Vuejs如果连接未处于“已连接”状态,则无法发送数据 | SignalR,Vuejs
【发布时间】:2021-10-09 01:20:48
【问题描述】:

我在这里搜索过类似的主题,但我仍然没有解决我的问题。也许有人可以帮我解决这个问题。

我的目标是显示来自各种服务的日志。为此,我使用带有 vuejs 的 signalR 作为客户端。我想通过按钮单击连接到服务组并获取日志。当我点击其他按钮时,我想离开组并加入另一个组。

selectItem(name) {
  this.groups.push(name)
  document.getElementById('messageList').innerHTML = ''
      
  const connection = new signalR.HubConnectionBuilder()
  .withUrl("http://localhost:5000/logs")
  .configureLogging(signalR.LogLevel.Information)
  .build()

  if (this.groups.length > 1) {
    let previousGroup = this.groups[this.groups.length - 2]
    connection.invoke("LeaveGroup", previousGroup)
    console.log('leaving group:', previousGroup)
  }

  connection.on("PushEventLog", (message) => {
    const div = document.createElement('div')
    div.textContent = message
    document.getElementById('messageList').appendChild(div)
  })

  connection.start().then(() => {
    connection.invoke("JoinGroup", name)
    console.log('joining group: ', name)
  })
}

在我第一次加入群组时一切正常,但是当我离开群组并想加入另一个群组时,我收到错误消息:

有什么帮助吗?

【问题讨论】:

    标签: vue.js signalr signalr-hub


    【解决方案1】:

    每次selectItem 运行时,您都会创建一个新连接。您应该将连接对象存储在某个地方,并且仅在它启动后使用它。

    在您的代码中添加了几个 cmets 以指出您做错了什么。

    // new connection object
    const connection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:5000/logs")
      .configureLogging(signalR.LogLevel.Information)
      .build()
    
      if (this.groups.length > 1) {
        let previousGroup = this.groups[this.groups.length - 2]
        // using new connection that hasn't started yet
        connection.invoke("LeaveGroup", previousGroup)
        console.log('leaving group:', previousGroup)
      }
    

    【讨论】:

      【解决方案2】:

      我找到了解决方案 - 我已将连接和日志移至创建的挂钩。工作代码如下。

      methods: {
        selectItem(name, i) {
          this.groups.push(name)
          document.getElementById('messageList').innerHTML = ''
      
          if (this.groups.length > 1) {
            let previousGroup = this.groups[this.groups.length - 2]
            this.connection.invoke("LeaveGroup", previousGroup)
          } else {
            this.connection.invoke("JoinGroup", name)
          }
        }
      }
      created() {
        this.connection = new signalR.HubConnectionBuilder()
        .withUrl("http://localhost:5000/logs")
        .build()
      
        this.connection.start()
      
        this.connection.on("PushEventLog", (message) => {
          const div = document.createElement('div')
          div.textContent = message
          document.getElementById('messageList').appendChild(div)
        })
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-21
        • 2020-05-16
        • 2020-01-21
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 2021-05-25
        • 1970-01-01
        • 2017-12-24
        相关资源
        最近更新 更多