FPF   付鹏篚的笔记
  • 主页
  • 归档
  • 分类
  • 标签
  • 关于

付鹏篚

  • 主页
  • 归档
  • 分类
  • 标签
  • 关于
Quiet主题
  • 配置
  • signalr

signalr配置与使用指南

付鹏篚
通信

2021-07-11 20:00:00

文章目录
  1. 安装
  2. 使用
    1. Home.vue
  3. 日志等级
  4. 客户端调用服务端
  5. 服务端调用客户端
  6. 服务器端代码示例

安装

npm install @microsoft/signalr

使用

const signalR = require("@microsoft/signalr");
// 创建连接
const connection = new signalR.HubConnectionBuilder()
  .withUrl("http://localhost:5000/chathub", {})
  .configureLogging(signalR.LogLevel.Error)  // 日志等级
  .build();
  
 // 客户端注册事件
 // 注册事件回调参数个数应与后端一致
connection.on("RecieveMessage", (user, message) => {
  console.log(user, message);
});
// 建议将参数合并到一个对象中
connection.on("RecieveMessage", data => {
  let [user, message] = data;
  console.log(user, message);
});


// 生命周期
connection.onreconnecting(error => {
  console.log(error);
});
connection.onreconnected(connectionId => {
  console.log(connectionId);
});
connection.onclose(error => {
  console.log(error);
});
// 自定义开始函数
async start() {
    try {
        await connection.start();
        console.log("SignalR Connected.");
    } catch (err) {
        console.log(err);
        setTimeout(this.start(), 5000);
    }
}

// 启动
start()
// 在启动完成立即发送请求
start()
  .then(()=>connection.invoke("MethodName", params))
  .catch(error => console.log(error));

Home.vue
<template>
  <div>
    <input v-model="user" type="text" />
    <input v-model="message" type="text" /><br />
    <button @click="sendMsg">发送</button>
    <hr />
    <ul>
      <li v-for="(item, index) in msgList" :key="index">
        {{ item.user }}:&nbsp;&nbsp;&nbsp;&nbsp;{{ item.msg }}
      </li>
    </ul>
  </div>
</template>

<script>
const signalR = require("@microsoft/signalr");
export default {
  data() {
    return {
      connection: "",
      user: "",
      message: "",
      msgList: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl("http://localhost:5000/chathub", {})
        .configureLogging(signalR.LogLevel.Error)
        .build();
      this.connection.on("ReceiveMessage", data => {
        this.msgList.push(data);
      });
      this.connection.start();
    },
    sendMsg() {
      let params = {
        user: this.user,
        message: this.message
      };
      this.connection.invoke("SendMessage", params);
    }
  }
};
</script>

<style></style>

日志等级

signalR.LogLevel.Error:错误消息。 Error仅记录消息。
signalR.LogLevel.Warning:有关潜在错误的警告消息。 日志 Warning 和 Error 消息。
signalR.LogLevel.Information:无错误的状态消息。 日志 Information 、 Warning 和 Error 消息。
signalR.LogLevel.Trace:跟踪消息。 记录所有内容,包括中心和客户端之间传输的数据。

客户端调用服务端

connection.invoke("SendMessage", ...params);
connection.invoke("SendMessage", user, message);
// SendMessage 是服务端定义的的方法
// ...params 参数列表,可以有多个参数,参数和服务端定义的方法参数个数,类型相同

服务端调用客户端

connection.on("ReceiveMessage",data=>{
    console.log(data)
    // do something
});
// ReceiveMessage 服务端调用客户端的方法名
// data 传递到客户端的参数

服务器端代码示例

// 客户端调用服务端的方法
public async Task SendMessage(string user, string message)
{
   // 服务端主动调用客户端的方法
    await Clients.All.SendAsync("ReceiveMessage", data);
}

// 常用方法
// 给所有人发送消息
await Clients.All.SendAsync("ReceiveMessage", data);
// 给组里所有人发消息
await Clients.Group("Users").SendAsync("ReceiveMsg", data);
// 给调用方法的那个人发消息
await Clients.Caller.SendAsync("ReceiveMessage", data);
// 给除了调用方法的以外所有人发消息
await Clients.Others.SendAsync("ReceiveMessage", data);
// 给指定connectionId的人发消息
await Clients.User(connectionId).SendAsync("ReceiveMessage", data);
// 给指定connectionId的人发消息
await Clients.Client(connectionId).SendAsync("ReceiveMessage", data);
// 给指定connectionId的人发消息,同时指定多个connectionId
await Clients.Clients(IReadOnlyList<> connectionIds).SendAsync("ReceiveMessage", data);
上一篇

图片防盗链

下一篇

VXE Table

©2025 By 付鹏篚. 主题:Quiet
Quiet主题