简体   繁体   English

Android应用没有从SignalR中心接收数据

[英]Android app did not receive data from SignalR hub

I already read these topics: 我已经阅读了这些主题:
how to use SignalR in Android 如何在Android中使用SignalR
Android Client doesn't get data but .net client getting data from SignalR server Android客户端无法获取数据,但.net客户端从SignalR服务器获取数据

I write a simple chat system with Android that works with SignalR. 我用Android编写了一个与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. 它应该是客户端发送消息(通过在服务器上调用SendMessage方法),服务器应该在客户端上调用NewMessage方法。

Here is my ChatHub class (simplified) written in C#. 这是我用C#编写的ChatHub类(简化)。

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);
        }
    }
}

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. 当android客户端连接到服务器时,在OnConnected方法上,连接ID将存储在_connectedClients并且它可以正常工作。

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 ChatHub类的SendMessage方法中,我们有android设备连接ID,我确定android设备在列表中

And here is my Andoird codes: 这是我的Andoird代码:

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
                }
        });

    }
}

In the above java code, invoking the sendMessage on the server works fine and the server get the messages. 在上面的java代码中,在服务器上调用sendMessage工作正常,服务器获取消息。
But the only problem is that the hub.on(...) or hub.subscribe(...) events are never be called by the server. 但唯一的问题是服务器永远不会调用hub.on(...)hub.subscribe(...)事件。
In a simple description, My app can send message, but can not receive message from the others. 在一个简单的描述中,我的应用程序可以发送消息,但无法接收来自其他人的消息。
Any suggestion will be appreciated. 任何建议将不胜感激。

For the futures this is the way I finally achieved the answer (please first read the question android codes): 对于期货这是我最终获得答案的方式(请先阅读android代码的问题):

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. 这就是我在本主题中解决问题的方法。

You does not provider parameters in your client-side which should be same as your side-site. 您不在客户端提供参数,这些参数应您的旁边站点相同 The code should be below: 代码应该如下:

      hub.on("NewMessage", new SubscriptionHandler1<String>() {
        @Override
        public void run(String message) {
            Log.d("<Debug", "new message received in `on`"); 
        }
    },String.class);  //do not forget say the String class in the end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM