断开连接后尝试连接到 SignalR 服务器时应用程序崩溃 [英] App crashes when trying to connect to SignalR server after disconnecting it

查看:55
本文介绍了断开连接后尝试连接到 SignalR 服务器时应用程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Xamarin Android 应用,该应用使用 SignalR 进行实时聊天.当我断开连接后再次尝试连接到服务器时,应用程序崩溃,当应用程序重新启动时,它连接正常.我有一个单例类,用于整个解决方案中的相同引用.单例类有以下方法连接到服务器:

I'm building a Xamarin Android app that uses SignalR for the purpose of real time chat. The app crashes when I try to connect to the server again after I disconnect it and when the app relaunches, it connects fine. I have a singleton class that used for the same reference across my solution. The singleton class has the following method to connect to the server:

public async Task<string> StartConnection()
    {
        hubConnection.Headers.Add("User-Agent", "mobile");
        hubConnection.Headers.Add("username", loggedUser);
        try
        {
            await hubConnection.Start();
            return "Connected..";
        }
        catch (Exception e)
        {
            return e.Message;
        }

    }

以下方法断开连接:

public void StopConnection()
    {
        hubConnection.Stop();

    }

连接是在app的MainActivity中启动的,如下图:

The connection is started in the MainActivity of the app as shown in below:

      Task.Factory.StartNew(async () =>
        {
            await SignalRClientHelper.StartConnection();
            SignalRClientHelper.InvokeGetPendingConversations(loggedonuser.UserName);

        });

用户注销时连接断开,如下图:

The connection is disconnected when the user is logged out as shown below:

SignalRClientHelper.StopConnection();

客户端可以第一次连接到signalR服务器没有任何问题,但是当他们注销并再次登录应用程序时,应用程序在第二次尝试服务器时崩溃.这是错误日志:

The client can connect to the signalR server for the first time without any problem but when they logout and login in to the app again, the app crashes when trying to server the second time. Here's the error log:

    ava.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
    ... 2 more
Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.InvalidOperationException: Data cannot be sent because the connection is in the disconnected state. Call start before sending any data.
  at Microsoft.AspNet.SignalR.Client.Connection.Send (System.String data) [0x0001e] in <filename unknown>:0 
  at Microsoft.AspNet.SignalR.Client.Hubs.HubProxy.Invoke[TResult,TProgress] (System.String method, System.Action`1 onProgress, System.Object[] args) [0x000e1] in <filename unknown>:0 
  at Microsoft.AspNet.SignalR.Client.Hubs.HubProxy.Invoke[T] (System.String method, System.Object[] args) [0x00000] in <filename unknown>:0 
  at Microsoft.AspNet.SignalR.Client.Hubs.HubProxy.Invoke (System.String method, System.Object[] args) [0x00000] in <filename unknown>:0 
  at Yourtime.SignalRClientHelper+<InvokeSendMessage>d__11.MoveNext () [0x0000d] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <filename unknown>:0 
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (System.Object state) [0x00000] in <filename unknown>:0 
  at Android.App.SyncContext+<Post>c__AnonStorey0.<>m__0 () [0x00000] in <filename unknown>:0 
  at Java.Lang.Thread+RunnableImplementor.Run () [0x0000b] in <filename unknown>:0 
  at Java.Lang.IRunnableInvoker.n_Run (IntPtr jnienv, IntPtr native__this) [0x00009] in <filename unknown>:0 
  at (wrapper dynamic-method) System.Object:44f67f43-349f-4a1b-8234-1604bc812b68 (intptr,intptr)
    at mono.java.lang.RunnableImplementor.n_run(Native Method)
    at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:29)
    at android.os.Handler.handleCallback(Handler.java:605)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4511)

有人知道这里可能有什么问题吗?

Does anyone have any idea what might be wrong here?

推荐答案

SignalR 断开连接有点问题 IMO,但您的错误清楚地表明您正在尝试在断开连接状态下调用某些内容.

SignalR disconnection is bit buggy IMO, but your error clearly says you are trying to invoke something when in disconnected state.

我建议您按如下方式更改连接/断开连接的方式:

I suggest you change the way you connect/disconnect as follows:

断开连接

var connectionToDispose = _connection; // _connection is the current connection
_connection = null;
_proxy = null;

// connection disposing can block the UI thread for about 20 seconds
// this doesn´t always happen but just in case we run it on a new thread
Task.Run(() =>
{
    try
    {
        connectionToDispose.Dispose();
    }
    catch (Exception ex)
    {
        _tracer?.WriteLine($"[{_className}] Connection could not be disposed: {ex.Message}");
    }
});

连接

if (_connection != null)
{
    return false;
}

// always create a new Hub
_connection = new HubConnection(_endpointUri);
// TODO add headers
// TODO create proxy again and subscribe to server events (proxy.On...), etc

try
{
    _tracer?.WriteLine($"[{_className}] CONNECTING...");
    await _connection.Start();

    return true;
}
catch (Exception ex)
{
    _tracer?.WriteLine($"[{_className}] CONNECTION START ERROR: {ex.Message}");
    return false;
}

仅供参考,看看这个.我在一个应用程序中使用过多次连接/断开连接没有问题.你可以从中汲取一些想法.

Just for reference, take a look a this class. I´ve used in an app that connects/disconnects many times with no issues. You can take some ideas from it.

这篇关于断开连接后尝试连接到 SignalR 服务器时应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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