vue中使用signalR

安装

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);
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值