接收數據我已經閱讀這些主題:
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(...)
事件永遠不會被服務器調用。
在一個簡單的描述中,我的應用程序可以發送消息,但不能接收其他消息。
任何建議將不勝感激。
看到這個http://stackoverflow.com/a/42527962/1770868 –