会挽雕弓如满月,西北望,射天狼。这篇文章主要讲述Android signalR相关的知识,希望能为你提供帮助。
网上文章繁多,因各种版本混乱,有时很难找到方法,有的已经修复,有的已经过时,本文以当时实际情况的记录,不代表下个版本的情况,请注意各组件的版本对应。
关于服务端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"> & nbsp; < /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"> & nbsp; < /div> < div class="row"> < div class="col-6"> < input type="button" id="sendButton" value="https://www.songbingjia.com/android/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="https://www.songbingjia.com/android/~/js/signalr/dist/browser/signalr.js"> < /script> @*< script src="https://www.songbingjia.com/android/~/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, "& amp; ").replace(/< /g, "& lt; ").replace(/> /g, "& gt; "); 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>
【Android signalR】关于发布,我这里本地调试正常,上传后部署模式只有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(); }
推荐阅读
- ApplicationRunner接口
- Android9.0 Settings 修改踩坑记录
- springboot 微信支付里的app支付坑注意,requestPayment,支付报错,"errMsg":"requestPayment:fail:[payment微
- react app相关知识
- 微信中域名被封-页面添加遮罩层提示用户使用浏览器打开(或下载APP)
- create-react-app兼容ie9配置
- Spring Boot中配置文件application.properties里面配置项的引用
- 浅谈Mybatis通用Mapper使用方法_java - JAVA
- application.properties和application.yml文件的区别