• asp.net core signalR (1)


    服务端SignalR支持

    // 加入signalR,需要cors支持
    builder.Services.AddSignalR();
    string[] urls = { "http://localhost:3000" };
    builder.Services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
        .AllowAnyMethod().AllowAnyHeader().AllowCredentials());
    });
    
    app.UseCors();
    app.MapHub<MyChatHub>("/hubs/chatroomhub");
    
        public class MyChatHub : Hub
        {
            public Task SendPublicMessage(string message)
            {
                string connId = Context.ConnectionId;
                string msg = $"{connId} {DateTime.Now}:{message}";
    
                return Clients.All.SendAsync("PublicMessageReceived", msg);
            }
        }
    

    client端SignalR支持

    . 使用yarn管理包,Vue作为client端框架

    yarn create @vitejs/app chatroom
    npm install @microsoft/signalr
    
    yarn
    yarn dev
    
    <template>
      <div>
        <input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnkeypress" />
        <ul>
          <li v-for="(msg,index) in state.messages" :key="index">{{msg}}</li>
        </ul>
      </div>
    </template>
    
    
    <script>
    import { reactive, onMounted } from "vue";
    import * as signalR from "@microsoft/signalr";
    
    let connection;
    
    export default {
      name: "Login",
      setup() {
        const state = reactive({ userMessage: "", messages: [] });
        const txtMsgOnkeypress = async function (e) {
          if (e.keyCode != 13) return;
          await connection.invoke("SendPublicMessage", state.userMessage);
          state.userMessage = "";
        };
    
        onMounted(async function () {
          connection = new signalR.HubConnectionBuilder()
            .withUrl("https://localhost:7115/hubs/chatroomhub")
            .withAutomaticReconnect()
            .build();
    
          await connection.start();
          connection.on("PublicMessageReceived", (msg) => {
            state.messages.push(msg);
          });
        });
    
        return { state, txtMsgOnkeypress };
      },
    };
    </script>
    
  • 相关阅读:
    blk_update_request: I/O error, dev fd0, sector 0
    将MySQL数据迁移到Redis
    专职DBA-MySQL DAL(Data Access Layer)中间件总结
    搞笑聊天(一)
    看图写话(一)
    NFS存储服务
    rsync备份服务
    专职DBA-使用Python操作MySQL数据库
    如何解决SecureCRT无法选择Monaco等其他字体
    MySQL架构类型
  • 原文地址:https://www.cnblogs.com/mryux/p/15940429.html
Copyright © 2020-2023  润新知