2016-09-20 46 views
8

接收數據我已經閱讀這些主題:
how to use SignalR in Android
Android Client doesn't get data but .net client getting data from SignalR serverAndroid應用程序並沒有從SignalR樞紐

我寫了Android一個簡單的聊天系統,與SignalR工作。
應該向客戶端發送消息(通過在服務器上調用SendMessage方法),服務器應該在客戶端上調用NewMessage方法。

這是我的ChatHub類(簡體)用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並能正常工作。

ChatHub類的SendMessage方法,我們有Android設備連接ID,我敢肯定的是,Android設備列表

這裏是我的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 
       } 
     }); 

    } 
} 

在上面的java代碼中,調用服務器上的sendMessage工作正常,服務器獲取消息。
但唯一的問題是hub.on(...)hub.subscribe(...)事件永遠不會被服務器調用。
在一個簡單的描述中,我的應用程序可以發送消息,但不能接收其他消息。
任何建議將不勝感激。

+0

看到這個http://stackoverflow.com/a/42527962/1770868 –

回答

6

對於期貨,這是我終於實現了答案(請您先閱讀問題的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()); 

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

    } 
} 

重要提示:
代碼的優先級很重要。這是我如何解決我在這個話題中的問題。

+0

嗨!感謝您的回答,我面臨同樣的問題,它解決了我的問題。我在「onMessageReceived」方法中得到了服務器的響應,而我並不期待它。無論如何,我觀察到連接中斷,並且一段時間後我停止接收消息。可能是什麼原因? –

+1

在'Configuration'方法''startup'類中的服務器中,我們編寫這些:'GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromMinutes(110); GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromMinutes(30); GlobalHost.Configuration.KeepAlive = TimeSpan.FromMinutes(10);'。順便說一句,我們正在使用WebApi。 @UmarFarooque – rejnev

+0

謝謝,如果超時設置爲很短的時間,我會從後端檢查它。 –

2

您不提供參數在您的客戶端應該是相同作爲您的站點。該代碼應低於:

 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