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、  运行效果

 

posted @   爱生活,爱代码  阅读(105)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示