网上文章繁多,因各种版本混乱,有时很难找到方法,有的已经修复,有的已经过时,本文以当时实际情况的记录,不代表下个版本的情况,请注意各组件的版本对应。
关于服务端
Visual Studio 2019 16.4.2
建立网站项目,选择ASP.NET Core Web应用程序,不要选择ASP.NET Web(.NET Framwork)
.NetCore框架:3.1.0
AspNetCore框架 3.1.0
项目中引用的是 using Microsoft.AspNetCore.SignalR;(Framework引用的是using Microsoft.AspNet.SignalR;)
ChatHub.cs
using Microsoft.AspNetCore.SignalR; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ShenghuaSignalR.Hubs { public class ChatHub:Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } }
修改Startup.cs,添加画线部分就可以
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SignalRChat.Hubs; namespace SignalRChat { 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.AddRazorPages(); 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("/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.MapRazorPages(); endpoints.MapHub<ChatHub>("/chatHub"); }); } } }
用于测试的网页端js
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <div class="container"> <div class="row"> </div> <div class="row"> <div class="col-2">User</div> <div class="col-4"><input type="text" id="userInput" /></div> </div> <div class="row"> <div class="col-2">Message</div> <div class="col-4"><input type="text" id="messageInput" /></div> </div> <div class="row"> </div> <div class="row"> <div class="col-6"> <input type="button" id="sendButton" value="Send Message" /> </div> </div> </div> <div class="row"> <div class="col-12"> <hr /> </div> </div> <div class="row"> <div class="col-6"> <ul id="messagesList"></ul> </div> </div> <script src="~/js/signalr/dist/browser/signalr.js"></script> @*<script src="~/js/chat.js"></script>*@ <script> "use strict"; var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build(); //Disable send button until connection is established document.getElementById("sendButton").disabled = true; connection.on("ReceiveMessage", function (user, message) { var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); var encodedMsg = user + " says " + msg; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().then(function () { document.getElementById("sendButton").disabled = false; }).catch(function (err) { return console.error(err.toString()); }); document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); }); </script>
关于发布,我这里本地调试正常,上传后部署模式只有x86“独立”成功运行网站。
关于客户端
Android Studio 3.5.3 官方版本 java
引用:
implementation ‘com.microsoft.signalr:signalr:3.0.0-preview3-19153-02‘
implementation group: ‘org.slf4j‘, name: ‘slf4j-android‘, version: ‘1.7.7‘
调用部分:
HubConnection hubConnection = HubConnectionBuilder.create(url) .build(); hubConnection.on("ReceiveMessage", (user,message) -> { Log.e(TAG, "hubConnection: "+user+":"+message);
showMessage(user,message);
}, String.class,String.class);
//This is a blocking call
hubConnection.start().blockingAwait();
hubConnection.send("SendMessage", "android",output);
需要这个来调用主线程
private void showMessage(String user,String message ){
makeToastByAsyncTask(user+":"+message,getApplicationContext());
}
private static void makeToastByAsyncTask(final String msg, final Context context) { AsyncTask asyncTask = new AsyncTask() { @Override protected Object doInBackground(Object[] params) { return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } @Override protected void onProgressUpdate(Object[] values) { super.onProgressUpdate(values); } }; asyncTask.execute(); }