1. 程式人生 > 其它 >SignalR系列文章02---netCoreMvc建立Demo

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