Xamarin ClientWebSocket ...连接丢失后无法重新连接

时间:2015-08-11 06:22:22

标签: c# android xamarin websocket clientwebsocket

我正在使用ClientWebSocket开发Android应用程序。

当我启动应用程序时,如果服务器正在运行,一切正常。

停止服务器后,客户端无法重新连接到服务器,无法接收消息。我注意到在停止服务器后,clientwebsocket的状态仍为“Open”!

如果我启动应用程序然后启动服务器,则客户端无法连接!

这是代码:

    string ip = "192.168.1.142";
    int port = 9000;
    private const int ReceiveChunkSize = 1024;
    private const int SendChunkSize = 1024;
    private ClientWebSocket _ws;
    private readonly Uri _uri;
    private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
    private readonly CancellationToken _cancellationToken;

准备客户:

        _ws = new ClientWebSocket ();
        _ws.Options.KeepAliveInterval = TimeSpan.FromSeconds (20);
        _uri = new Uri ("ws://"+ip+":"+port);
        _cancellationToken = _cancellationTokenSource.Token;

连接方法:

public async void ConnectAsync()
    {
        await Task.Run (() => {
            try {
                var tk = _ws.ConnectAsync (_uri, _cancellationTokenSource.Token);
                tk.Wait(4000);
            if (tk.IsCompleted) {
                //CallOnConnected ();
                StartListen ();
                }
            } 
            catch 
            { 
            }
        });
    }

收听收入消息:

private async void StartListen()
    {
        var buffer = new byte[ReceiveChunkSize];

        try
        {
            while (_ws.State == WebSocketState.Open)
            {
                var stringResult = new StringBuilder();


                WebSocketReceiveResult result;
                do
                {
                    result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), _cancellationToken);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await
                        _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                        //CallOnDisconnected();
                    }
                    else
                    {
                        var str = Encoding.UTF8.GetString(buffer, 0, result.Count);
                        stringResult.Append(str);
                    }

                } while (!result.EndOfMessage);

                //CallOnMessage(stringResult);

            }
        }
        catch (Exception)
        {
            //CallOnDisconnected();
        }
        finally
        {
            _ws.Dispose();
        }
    }

在MainActivity中,我使用计时器重新连接:

void Try_Connect(){
        if ((my_clientwebsocket.Connection_Status == System.Net.WebSockets.WebSocketState.Open)|(my_clientwebsocket.Connection_Status == System.Net.WebSockets.WebSocketState.Connecting)) {
            return;
        }

            new Thread (new ThreadStart (delegate { 
            RunOnUiThread (() => {
                    try {
                        my_clientwebsocket.ConnectAsync();
                    } catch {
                    }
            });
            })).Start ();


    }

有什么不对?!

感谢您的帮助

0 个答案:

没有答案