Android应用未从SignalR集线器接收数据 [英] Android app did not receive data from SignalR hub

查看:228
本文介绍了Android应用未从SignalR集线器接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了以下主题:

如何在Android中使用SignalR

I already read these topics:
how to use SignalR in Android
Android Client doesn't get data but .net client getting data from SignalR server

我写了一个简单的

应该由客户端发送消息(通过在服务器上调用 SendMessage 方法),服务器应在客户端上调用 NewMessage 方法。

I write a simple chat system with Android that works with SignalR.
It is supposed to the clients send messages (by calling SendMessage method on the server) and the server should call the NewMessage method on the clients.

这是我用C#编写的 ChatHub 类(简体)。

Here is my ChatHub class (simplified) written in C#.

public class ChatHub : Hub
{
    // Store the clients connections Id
    static readonly List<string> _connectedClients;

    public override Task OnConnected()
    {
        // Keep connections id
        // This section works fine and when the android device connects to the server,
        // Its connection id will stored.
        _connectedClients.Add(Context.ConnectionId)

        //... other codes
    }

    public void SendMessage(string message)
    {
        foreach (var connectionId in _connectedClients)
        {
            // according to the logs 
            // android device connection id exists here
            // and it works fine.
            Clients.Client(connectionId).NewMessage(message);
        }
    }
}

当android客户端连接到服务器上,在 OnConnected 方法上,连接ID将存储在 _connectedClients 中,并且可以正常工作。

When the android client connects to the server, On the OnConnected method, the connection id will be stored in the _connectedClients and it works fine.

ChatHub 类的 SendMessage 方法中,我们有android设备连接ID,我确定android设备在列表中

In the SendMessage method of the ChatHub class, We have the android device connection id, and I'm sure that the android device is within the list

这是我的Andoird代码:

And here is my Andoird codes:

public class ChatActivity extends AppCompatActivity
{
    // private fields
    HubConnection connection;
    HubProxy hub;
    ClientTransport transport;

    protected void onCreate(Bundle savedInstanceState) {

        Logger logger = new Logger() {
            @Override
            public void log(String message, LogLevel logLevel) {
                Log.e("SignalR", message);
            }
        };

        Platform.loadPlatformComponent(new AndroidPlatformComponent());
        connection = new HubConnection("192.168.1.100");
        hub = connection.createHubProxy("chatHub"); // case insensitivity

        transport = new LongPollingTransport(connection.getLogger());

        // no difference when using this:
        //transport = new ServerSentEventsTransport(connection.getLogger());

        // this event never fired!
        hub.subscribe(new Object() {
            public void NewMessage(String message)
            {
                Log.d("<Debug", "new message received in subscribe"); // won't work!
            }
        }

        // this event never fired!
        hub.on("NewMessage", new SubscriptionHandler() {
            @Override
            public void run() {
                Log.d("<Debug", "new message received in `on`"); // won't work!
            }
        });

        // connect to the server that works fine.
        SignalRFuture<Void> awaitConnection = connection.start(transport);
        try {
            awaitConnection.get(); // seems useless when using this or not!
        }
        catch (Exception ex) {
        }

        // this method works fine.
        hub.invoke("sendMessage", "this is a test message to the server")
        .done(new Action<Void>() {
                @Override
                public void run(Void aVoid) throws Exception {
                    Log.d("<Debug", "message sent."); // Works fine
                }
        });

    }
}

在上述 java中代码,在服务器上调用 sendMessage 可以正常工作,服务器会收到消息。

但是唯一的问题是<$服务器永远不会调用c $ c> hub.on(...)或 hub.subscribe(...)事件。

在一个简单的描述中,我的应用程序可以发送消息,但不能接收其他消息。

任何建议将不胜感激。

In the above java code, invoking the sendMessage on the server works fine and the server get the messages.
But the only problem is that the hub.on(...) or hub.subscribe(...) events are never be called by the server.
In a simple description, My app can send message, but can not receive message from the others.
Any suggestion will be appreciated.

推荐答案

对于期货,这是我最终实现答案的方式(请先阅读android代码问题):

For the futures this is the way I finally achieved the answer (please first read the question android codes):

public class ChatActivity extends AppCompatActivity
{
    // private fields
    HubConnection connection;
    HubProxy hub;
    ClientTransport transport;

    protected void onCreate(Bundle savedInstanceState) {

        Logger logger = new Logger() {
            @Override
            public void log(String message, LogLevel logLevel) {
                Log.e("SignalR", message);
            }
        };

        Platform.loadPlatformComponent(new AndroidPlatformComponent());
        connection = new HubConnection("192.168.1.100");
        hub = connection.createHubProxy("chatHub"); // case insensitivity

        /* ****new codes here**** */
        hub.subscribe(this);

        transport = new LongPollingTransport(connection.getLogger());

        /* ****new codes here**** */
        connection.start(transport);

        /* ****new codes here**** */
        /* ****seems useless but should be here!**** */
        hub.subscribe(new Object() {
            @SuppressWarnings("unused")
            public void newMessage(final String message, final String messageId, final String chatId,
                                   final String senderUserId, final String fileUrl, final String replyToMessageId) {


            }
        });


        /* ********************** */
        /* ****new codes here**** */
        /* **** the main method that I fetch data from server**** */
        connection.received(new MessageReceivedHandler() {
            @Override
            public void onMessageReceived(final JsonElement json) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        JsonObject jsonObject = json.getAsJsonObject();
                        Log.e("<Debug>", "response = " + jsonObject.toString());

                    }
                });
            }
        });
        /* ********************** */

    }
}

!重要说明:

代码的优先级很重要。这就是我如何解决此主题中的问题。

!important note:
The priority of the codes is important. this is how I fix my problem in this topic.

这篇关于Android应用未从SignalR集线器接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆