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="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, "&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>

 

關於發佈,我這裏本地調試正常,上傳後部署模式只有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(); }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章