首页 > 其他分享 >NETCORE + VUE + SignalR 消息通信

NETCORE + VUE + SignalR 消息通信

时间:2023-01-09 13:59:07浏览次数:51  
标签:function VUE return NETCORE app SignalR user msg message

 NETCORE + VUE + SignalR 消息通信

 

 分组通信:https://blog.csdn.net/qbc12345678/article/details/125215711

 

一. 创建 Net6 WebApi 项目

 NETCORE.TSignalR

1.  创建 通信组件类:CustomHub.cs

using Microsoft.AspNetCore.SignalR;

namespace NETCORE.TSignalR
{
    public class CustomHub : Hub
    {
        private readonly ILogger<CustomHub> _logger;

        public CustomHub(ILogger<CustomHub> logger)
        {
            _logger = logger;
        }

        public override Task OnConnectedAsync()
        {
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            return base.OnDisconnectedAsync(exception);
        }


        public Task SendMessageCaller( string msg)
        {
            _logger.LogInformation("接受数据{0}", msg);
            return Clients.Caller.SendAsync("ReceiveCaller", $"自已收到消息,回复信息:{msg}");
        }

        public Task SendMessage(string id, string msg)
        {
            _logger.LogInformation("接受数据{0},{1}", id, msg);
            return Clients.All.SendAsync("ReceiveMessage", $"全体人员注意,{msg},发送者:{id}");
        }


        public Task SendMessageOther(string id, string msg)
        {
            _logger.LogInformation("接受数据{0},{1}", id, msg);
            return Clients.Others.SendAsync("ReceiveMessage", $"其他人员注意,{msg},发送者:{id}");
        }
    }     
}

 

 

2. 在 program.cs 中, 注入服务

using NETCORE.TSignalR;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 注入SignalR所需服务
builder.Services.AddSignalR();

//解决跨域
builder.Services.AddCors(c =>
{
    c.AddPolicy("Any", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()//Ensures that the policy allows any header.
              .AllowAnyMethod();
    });
});


var app = builder.Build();

//解决跨域
app.UseCors("Any");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

 //开启路由节点 用来映射Signalr请求路径
app.MapHub<CustomHub>("/custom");
 
app.MapControllers();

app.Run();

 

 

 3. 启动项目

打开路径: https://localhost:7018/custom,出现【Connection ID required】表示服务启动成功。

 

 

 二. 创建2个 Vue 客户端

1. 项目初始化

vue init webpack-simple single2
vue init webpack-simple single3

 

 

2. 安装插件

npm install @aspnet/signalr

 

 

 3. Vue 页面

<template>
  <div class="home">
    <h1>前端演示SignalR</h1>
    <input v-model="user" type="text" />
    <input v-model="message" type="text" />
    <button @click="sendAll">发送全部</button>
    <button @click="sendOwn">对自己发送</button>
    <button @click="sendOther">对其他发送</button>
    <div>
      <ul v-for="(item, index) in messages" v-bind:key="index + 'itemMessage'">
        <li>{{ item.user }} says {{ item.message }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import * as signalR from "@aspnet/signalr";
export default {
  name: "Home",
  components: {},
  data() {
    return {
      user: "s2", //用户
      message: "22222", //消息
      connection: "", //signalr连接
      messages: [], //返回消息
    };
  },
  methods: {
    //给全部发送消息
    sendAll: function () {
      this.connection
        .invoke("SendMessage", this.user, this.message)
        .catch(function (err) {
          return console.error(err);
        });
    },
    //只给自己发送消息
    sendOwn: function () {
      this.connection
        .invoke("SendMessageCaller", this.message)
        .catch(function (err) {
          return console.error(err);
        });
    },

    //给其他人员发送消息
    sendOther: function () {
      this.connection
        .invoke("SendMessageOther", this.user, this.message)
        .catch(function (err) {
          return console.error(err);
        });
    },
  },
  created: function () {
    let thisVue = this;
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl("https://localhost:7018/custom", {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets,
      })
      .configureLogging(signalR.LogLevel.Information)
      .build();
    this.connection.on("ReceiveMessage", function (user, message) {
      debugger;
      thisVue.messages.push({ user, message });
      console.log({ user, message });
    });
    this.connection.on("ReceiveCaller", function (message) {
      debugger;
      let user = "自己"; //这里为了push不报错,我就弄了一个默认值。
      thisVue.messages.push({ user, message });
      console.log({ user, message });
    });
    this.connection.start();
  },
};
</script>

 

 

三. 测试

 

标签:function,VUE,return,NETCORE,app,SignalR,user,msg,message
From: https://www.cnblogs.com/1285026182YUAN/p/17036798.html

相关文章

  • 关于vue :style 的几种使用方式
    :style的使用一,最通用的写法 <p:style="{fontFamily:arr.conFontFamily,color:arr.conFontColor,backgroundColor:arr.conBgColor}">{{con.title}}</p>二,三元表......
  • Vue的hash/history模式
    hash路由模式URL中的hash值只是客户端的一种状态,向服务端发送请求的时候,hash部分不会被发送;hash值得改变会在浏览器的历史记增加访问记录,所以可以通过浏览器的回退......
  • vue3+vite2 vite.config.js 配置
    vite配置官方文档:https://cn.vitejs.dev/config/shared-options.html#base 开发服务器选项-serverserver:{//host:指定服务器应该监听哪个ip地址。如果设置为......
  • vue2 element-ui组件二封-表单组件-按钮封装
    这里是一段我们公司过往项目的代码(增删改查项目中的查询/重置按钮)<el-button@click="query()"type="primary"size="mini"><iclass="el-icon-search">查询</i><......
  • vue2组件props;computed监控变量,watch执行方法
    props:{mesData:{type:Object,//接受父组件值required:true,},tableLod:{type:Function,......
  • vue项目部署到IIS服务器
    步骤一:复制文件把build之后的文件(dist文件夹)拷贝到IIS存放网站文件的目录步骤二:在IIS中新建站点步骤三:下载安装模块:urlrewrite传送门:https://www.iis.net/downloads/m......
  • 前端 vue 静态页面
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"content="width=......
  • 手写获取手机验证码按钮-适用vue,uniapp
    template<uni-forms-itemlabel="验证码"name="code"style="position:relative;"><inputmaxlength="6"type="number......
  • 每日一题之Vue的异步更新实现原理是怎样的?
    最近面试总是会被问到这么一个问题:在使用vue的时候,将for循环中声明的变量i从1增加到100,然后将i展示到页面上,页面上的i是从1跳到100,还是会怎样?答案当然是只会显示100,并不会......
  • 前端二面经典vue面试题指南
    v-model的原理?我们在vue项目中主要使用v-model指令在表单input、textarea、select等元素上创建双向数据绑定,我们知道v-model本质上不过是语法糖,v-model在内部为......