• SignalR系列文章02---netCoreMvc创建Demo


    1、  新建.net core MVC项目,并引入nuget包

    2、  添加客户端库

    3、  修改startUp.cs文件,增加services.AddSignalR();和endpoints.MapHub<ServerHub>("/serverHub");

     public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllersWithViews();
                services.AddSignalR();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapHub<ServerHub>("/serverHub");
                });
            }
        }

    4、  新增ServerHub类

    public class ServerHub:Hub
        {
            public async Task Send(string message)
            {
                await Clients.All.SendAsync("sendMessage", message);
            }
        }

    5、  在Home/index.cshtml文件中加入如下的代码

    @{
        ViewBag.Title = "聊天窗口";
    }
    
    <h2>Chat</h2>
    
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    
    @section scripts
    {
        <!--引用SignalR库. -->
        <script src="~/lib/signalr/signalr.min.js"></script>
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
    
        <script>
            $(function () {
    
                let hubUrl = 'https://localhost:44360/serverHub';
                let hubConnection = new signalR.HubConnectionBuilder().withUrl(hubUrl).build();
    
                $('#sendmessage').click(function () {
                    hubConnection.invoke("Send", $('#message').val());
                    // 清空输入框信息并获取焦点
                    $('#message').val('').focus();
                });
                //服务器回调方法
                hubConnection.on("sendMessage", function (data) {
                    // 向页面添加消息
                    $('#discussion').append('<li><strong>' + htmlEncode(data)
                        + '</strong></li>');
                })
    
                hubConnection.start();
    
    
            });
    
            // 为显示的消息进行Html编码
            function htmlEncode(value) {
                var encodedValue = $('<div />').text(value).html();
                return encodedValue;
            }
        </script>
    }

    6、  运行效果

  • 相关阅读:
    《RabbitMQ 实战》读书笔记
    使用jstack命令查看CPU高占用的问题记录
    两种常见的单元测试方式(笔记)
    Apache Solr入门教程(转)
    搜索引擎选择: Elasticsearch与Solr(转)
    CopyOnWriteArrayList与Collections.synchronizedList的性能对比(转)
    理解list和vector的区别
    从上往下打印出二叉树的每个节点,同层节点从左至右打印。
    TypeError: Object function (req, res, next) { app.handle(req, res, next); } has no method 'configure'
    Cannot find module 'crc'
  • 原文地址:https://www.cnblogs.com/zhengwei-cq/p/15429147.html
Copyright © 2020-2023  润新知