コード例 #1
0
ファイル: PIPFile.cs プロジェクト: MattiusMatt/pipeditor
 public PIPFile(string filePath, string comPort, Int32 baudRate, DataReceived dataReceived)
 {
     this._filePath = filePath;
     this._dataReceived = dataReceived;
     this._arduino = new SerialPort(comPort, baudRate, Parity.None, 8);
     this._arduino.DataReceived += this._arduino_DataReceived;
     this._arduino.WriteBufferSize = 4096 * 10;
 }
コード例 #2
0
        /// <summary>
        /// 接收到数据
        /// </summary>
        /// <param name="ar"></param>
        public void ReceiveCallback(IAsyncResult ar)
        {
            ZXBC_UDPClient userver  = (ZXBC_UDPClient)ar.AsyncState;
            string         ConnName = "";

            try
            {
                if (userver.NetWork.Client != null)
                {
                    IPEndPoint fclient = userver.ipLocalEndPoint;
                    Byte[]     recdata = userver.NetWork.EndReceive(ar, ref fclient);
                    ConnName = userver.ipLocalEndPoint.Port + "->" + fclient.ToString();
                    if (DataReceived != null)
                    {
                        DataReceived.BeginInvoke(ConnName, recdata, null, null);//异步输出数据
                    }
                    if (lstClient.Contains(ConnName) == false)
                    {//新的客户端
                        lstClient.Add(ConnName);
                        BindLstClient();
                    }
                }
            }
            catch (ObjectDisposedException ex) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (userver.NetWork.Client != null)
                {
                    userver.NetWork.BeginReceive(new AsyncCallback(ReceiveCallback), userver);//继续异步接收数据
                }
            }
        }
コード例 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        private void Client_DataReceived(Sockets.EventArgs.DataReceivedArgs args)
        {
            string data = Encoding.UTF8.GetString(args.Data);

            if (dataPoints.Count == 0)
            {
                string startingData = data.Substring(data.IndexOf("{"));
                dataPoints.Add(startingData);
            }
            else
            {
                dataPoints.Add(data);
            }

            if (data.Contains("\r"))
            {
                string json = String.Join("", dataPoints.ToArray());
                dataPoints.Clear();

                ETCarsDataContainer deserializedData = JsonConvert.DeserializeObject <ETCarsDataContainer>(json);

                DataReceived?.Invoke(new ETCarsDataReceivedArgs(json, deserializedData.data));
            }
        }
コード例 #4
0
        public void Run(int port)
        {
            _listener.ConnectionRequestEvent += request =>
            {
                request.AcceptIfKey(ClientKey);
            };

            _listener.PeerConnectedEvent += peer =>
            {
                ClientConnected?.Invoke(peer.Id);
            };

            _listener.NetworkReceiveEvent += (peer, reader, method) =>
            {
                DataReceived?.Invoke(peer.Id, reader.GetRemainingBytes());
            };

            _listener.PeerDisconnectedEvent += (peer, info) =>
            {
                ClientDisconnected?.Invoke(peer.Id);
            };

            _server.Start(port);
        }
コード例 #5
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            // 超出数据接收间隔
            timer.Stop();

            // 解析数据
            var tempData = new byte[recvBuffer.Count];

            recvBuffer.CopyTo(tempData);
            recvBuffer.Clear();

            //字符转换
            var tempStrs = new List <string>();

            for (var i = 0; i < tempData.Length; i++)
            {
                tempStrs.Add(tempData[i].ToString("X2"));
            }
            string readString = string.Join(" ", tempStrs);

            Log.WriteLog("INFO-" + this.config.PortName + ":收到内容-" + readString);
            //触发整条记录的处理
            DataReceived?.Invoke(new DataReceivedEventArgs(readString));
        }
コード例 #6
0
        private void ReaderThreadBody(Stream stream)
        {
            var value = 0;

            while (value != -1)
            {
                try
                {
                    value = stream.ReadByte();
                    if (value != -1)
                    {
                        DataReceived?.Invoke(value);
                    }
                }
                catch (IOException)
                {
                    value = -1;
                    break;
                }
            }

            Logger.LogAs(this, LogLevel.Debug, "Client disconnected, stream closed.");
            writerCancellationToken.Cancel();
        }
コード例 #7
0
 protected virtual void OnDataReceived(ClientNode node, string message)
 {
     DataReceived?.Invoke(node, message);
 }
コード例 #8
0
 private void OnDataReceived(byte[] buf, int len)
 {
     DataReceived?.Invoke(buf, len);
 }
コード例 #9
0
 static void stdoutReader_DataReceivedEvent(object sender, DataReceived e)
 {
     print(e.Data + "  " + e.Data.Length);
 }
コード例 #10
0
ファイル: OpcHelper.cs プロジェクト: lxy-coding/LIMS.DC
 /// <summary>
 ///
 /// </summary>
 /// <param name="dataID"></param>
 /// <param name="value"></param>
 /// <param name="quality"></param>
 /// <param name="stamp"></param>
 private static void OpcGroup_DataReceived(int dataID, object value, string quality, DateTime stamp)
 {
     DataReceived?.Invoke(dataID, value, quality, stamp);
 }
コード例 #11
0
 private void InvokeDataReceived(TcpClient tcpClient, byte[] dataBytes)
 {
     Log.Debug($"Receive: {BitConverter.ToString(dataBytes)}");
     DataReceived?.Invoke(this, tcpClient, dataBytes);
 }
コード例 #12
0
ファイル: TcpServer.cs プロジェクト: chengxulvtu/SimpleTcp
        private async Task DataReceiver(ClientMetadata client)
        {
            Logger?.Invoke("[SimpleTcp.Server] Data receiver started for client " + client.IpPort);

            while (true)
            {
                try
                {
                    if (client.Token.IsCancellationRequested ||
                        !IsClientConnected(client.Client))
                    {
                        Logger?.Invoke("[SimpleTcp.Server] Client " + client.IpPort + " disconnected");
                        break;
                    }

                    if (client.Token.IsCancellationRequested)
                    {
                        Logger?.Invoke("[SimpleTcp.Server] Cancellation requested (data receiver for client " + client.IpPort + ")");
                        break;
                    }

                    byte[] data = await DataReadAsync(client);

                    if (data == null)
                    {
                        await Task.Delay(30);

                        continue;
                    }

                    DataReceived?.Invoke(this, new DataReceivedFromClientEventArgs(client.IpPort, data));
                    _Stats.ReceivedBytes += data.Length;
                    UpdateClientLastSeen(client.IpPort);
                }
                catch (SocketException)
                {
                    Logger?.Invoke("[SimpleTcp.Server] Data receiver socket exception (disconnection) for " + client.IpPort);
                }
                catch (Exception e)
                {
                    Logger?.Invoke("[SimpleTcp.Server] Data receiver exception for client " + client.IpPort + ":" +
                                   Environment.NewLine +
                                   e.ToString() +
                                   Environment.NewLine);

                    break;
                }
            }

            Logger?.Invoke("[SimpleTcp.Server] Data receiver terminated for client " + client.IpPort);

            if (_ClientsKicked.ContainsKey(client.IpPort))
            {
                ClientDisconnected?.Invoke(this, new ClientDisconnectedEventArgs(client.IpPort, DisconnectReason.Kicked));
            }
            else if (_ClientsTimedout.ContainsKey(client.IpPort))
            {
                ClientDisconnected?.Invoke(this, new ClientDisconnectedEventArgs(client.IpPort, DisconnectReason.Timeout));
            }
            else
            {
                ClientDisconnected?.Invoke(this, new ClientDisconnectedEventArgs(client.IpPort, DisconnectReason.Normal));
            }

            DateTime removedTs;

            _Clients.TryRemove(client.IpPort, out ClientMetadata destroyed);
            _ClientsLastSeen.TryRemove(client.IpPort, out removedTs);
            _ClientsKicked.TryRemove(client.IpPort, out removedTs);
            _ClientsTimedout.TryRemove(client.IpPort, out removedTs);
            client.Dispose();
        }
コード例 #13
0
ファイル: TCPIPStack.cs プロジェクト: Orvid/Cosmos
        /// <summary>
        /// Subscribe to a UDP port to listen to data received on a specific port number
        /// <remarks>Only one listener allowed</remarks>
        /// </summary>
        /// <param name="port">Port number to listen on</param>
        /// <param name="callback"><see cref="DataReceived"/> delegate to call when data is received</param>
        public static void SubscribeUDPPort(UInt16 port, DataReceived callback)
        {
            if (udpClients.ContainsKey(port) == true)
            {
                throw new ArgumentException("Port is already subscribed to", "port");
            }

            udpClients.Add(port, callback);
        }
コード例 #14
0
ファイル: IOPool.cs プロジェクト: m9ra/Hipiol
        /// <summary>
        /// Set handlers for network data manipulation.
        /// </summary>
        /// <param name="dataReceivedHandler">Received data are reported by this handler.</param>
        /// <param name="dataBlockSentHandler">Successful completition of data block sending is reporeted by this handler. It is called just once for every <see cref="Send"/> if sending is successful.</param>
        public void SetDataHandlers(DataReceived dataReceivedHandler, DataBlockSent dataBlockSentHandler)
        {
            if (dataReceivedHandler == null)
                throw new ArgumentNullException("dataReceivedHandler");

            if (dataBlockSentHandler == null)
                throw new ArgumentNullException("dataBlockSentHandler");

            if (_dataReceivedHandler != null || _dataBlockSentHandler != null)
                throw new NotSupportedException("Cannot change data handlers.");

            _dataReceivedHandler = dataReceivedHandler;
            _dataBlockSentHandler = dataBlockSentHandler;
        }
コード例 #15
0
 public void OnDataReceived(string data)
 {
     ReceivedData.Add(data);
     DataReceived?.Invoke(this, data);
 }
コード例 #16
0
ファイル: DataReceiver.cs プロジェクト: SteamDiver/Kursach
        private void PortOnDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var sp = (SerialPort)sender;

            DataReceived?.Invoke(sp.ReadExisting());
        }
コード例 #17
0
ファイル: MainForm.cs プロジェクト: junian/SerialDeviceEmu
        private void MainForm_Load(object sender, EventArgs e)
        {
            LoadSettings();
            LoadPortNames();

            textLog.AppendText(FormatLogMessage("INFO", "application started"));
            SetSelectedPortLabel("-");
            dataReceived = new DataReceived(ViewReceivedMessage);

            comboBoxPortNames.DataBindings.Add("Enabled", groupBoxDeviceSettings, "Enabled");
            buttonRefresh.DataBindings.Add("Enabled", groupBoxDeviceSettings, "Enabled");
            comboBoxParity.DataSource = (Parity[]) Enum.GetValues(typeof(Parity));
            comboBoxHandshake.DataSource = (Handshake[]) Enum.GetValues(typeof(Handshake));

            //initialize StopBits inside radioButton Tag
            radioButtonStopBits1.Tag = StopBits.One;
            radioButtonStopBits15.Tag = StopBits.OnePointFive;
            radioButtonStopBits2.Tag = StopBits.Two;

            AppSettings.Instance.LoadCurrentAppSettings();

            bindingSource = new BindingSource();
            bindingSource.DataSource = AppSettings.Instance.SDEmuSetting;
            serialSettingBindingSource = new BindingSource();
            serialSettingBindingSource.DataSource = AppSettings.Instance.SDEmuSetting.SerialSetting;

            this.DataBindings.Add("SerialStopBits", serialSettingBindingSource, "StopBits");
            this.DataBindings.Add("SerialDataBits", serialSettingBindingSource, "DataBits");

            comboBoxBaudRate.DataBindings.Add("Text", serialSettingBindingSource, "BaudRate");
            comboBoxParity.DataBindings.Add("SelectedItem", serialSettingBindingSource, "Parity");
            comboBoxHandshake.DataBindings.Add("SelectedItem", serialSettingBindingSource, "Handshake");

            radioStringMessage.DataBindings.Add("Checked", bindingSource, "IsStringMode");
            radioHexMessage.DataBindings.Add("Checked", bindingSource, "IsHexMode");

            checkBoxCR.DataBindings.Add("Checked", bindingSource, "IsEndedWithCR");
            checkBoxLF.DataBindings.Add("Checked", bindingSource, "IsEndedWithLF");
        }
コード例 #18
0
ファイル: TcpClient.cs プロジェクト: RSBlek/vRubinum2
 private void OnDataReceived(byte[] data)
 {
     DataReceived?.Invoke(data);
 }
コード例 #19
0
ファイル: Communication.cs プロジェクト: windr00/TestClient
	public void AddNetworkListeners(NetworkConnected netConCall, DataSent dataSentCall, DataReceived dataRecvCall, NetworkError netErrorCall) {
		OnNetworkConnected += netConCall;
		OnDataSent += dataSentCall;
		OnDataReceived += dataRecvCall;
		OnNetworkError += netErrorCall;
	}
コード例 #20
0
 public void RaiseEvent(object sender, IOBDData data, DateTime timestamp) => DataReceived?.Invoke(sender, new DataReceivedEventArgs <T>((T)data, timestamp));
コード例 #21
0
 protected virtual void OnDataReceived(DataReceivedEventArg <TPacket> e)
 {
     DataReceived?.Invoke(this, e);
 }
コード例 #22
0
 private void handleDataReceived(
     Object sender,
     MessageEventArgs eventArgs) =>
 DataReceived?.Invoke(eventArgs.RawData);
コード例 #23
0
 private void OnDataReceived(Stream clientStream, String message)
 {
     DataReceived?.Invoke(clientStream, message);
 }
コード例 #24
0
 static void stderrReeader_DataReceivedEvent(object sender, DataReceived e)
 {
     print(e.Data);
 }
コード例 #25
0
ファイル: Client.cs プロジェクト: bjorndaniel/DTLS.Net
        private void ProcessRecord(DTLSRecord record)
        {
            try
            {
#if DEBUG
                Console.WriteLine(record.RecordType.ToString());
#endif
                switch (record.RecordType)
                {
                case TRecordType.ChangeCipherSpec:
                    if (_ServerEpoch.HasValue)
                    {
                        _ServerEpoch++;
                        _ServerSequenceNumber = 0;
                        _EncyptedServerEpoch  = _ServerEpoch;
                    }
                    break;

                case TRecordType.Alert:
                    AlertRecord alertRecord;
                    try
                    {
                        if ((_Cipher == null) || (!_EncyptedServerEpoch.HasValue))
                        {
                            alertRecord = AlertRecord.Deserialise(record.Fragment);
                        }
                        else
                        {
                            long   sequenceNumber = ((long)record.Epoch << 48) + record.SequenceNumber;
                            byte[] data           = _Cipher.DecodeCiphertext(sequenceNumber, (byte)TRecordType.Alert, record.Fragment, 0, record.Fragment.Length);
                            alertRecord = AlertRecord.Deserialise(data);
                        }
                    }
                    catch
                    {
                        alertRecord = new AlertRecord
                        {
                            AlertLevel = TAlertLevel.Fatal
                        };
                    }
                    if (alertRecord.AlertLevel == TAlertLevel.Fatal)
                    {
                        _Connected.Set();
                        //Terminate
                    }
                    else if ((alertRecord.AlertLevel == TAlertLevel.Warning) || (alertRecord.AlertDescription == TAlertDescription.CloseNotify))
                    {
                        if (alertRecord.AlertDescription == TAlertDescription.CloseNotify)
                        {
                            SendAlert(TAlertLevel.Warning, TAlertDescription.CloseNotify);
                            _Connected.Set();
                        }
                        //_Sessions.Remove(session, address);
                    }
                    break;

                case TRecordType.Handshake:
                    ProcessHandshake(record);
                    _ServerSequenceNumber = record.SequenceNumber + 1;
                    break;

                case TRecordType.ApplicationData:
                    if (_Cipher != null)
                    {
                        long   sequenceNumber = ((long)record.Epoch << 48) + record.SequenceNumber;
                        byte[] data           = _Cipher.DecodeCiphertext(sequenceNumber, (byte)TRecordType.ApplicationData, record.Fragment, 0, record.Fragment.Length);
                        DataReceived?.Invoke(record.RemoteEndPoint, data);
                    }
                    _ServerSequenceNumber = record.SequenceNumber + 1;
                    break;

                default:
                    break;
                }
            }
#if DEBUG
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                StackFrame callStack = new StackFrame(1, true);
                Console.WriteLine($"Exception! Type: { ex.GetType()}\n\tData: { ex.Data.Count}\n\tMessage: { ex.Message}\n\tSource: { ex.Source}\n\t" +
                                  $"StackTrace: { ex.StackTrace}\n\tFile: {callStack.GetFileName()}\n\t" +
                                  $"Line: {callStack.GetFileLineNumber()}");
#else
            catch
            {
#endif
            }
        }
コード例 #26
0
 internal void HandleDataReceived(object sender, DataReceivedFromServerEventArgs args)
 {
     DataReceived?.Invoke(sender, args);
 }
コード例 #27
0
        private async Task startReceiving(WebSocket socket)
        {
            try
            {
                while (true)
                {
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
                    // Do a 0 byte read so that idle connections don't allocate a buffer when waiting for a read
                    var result = await socket.ReceiveAsync(Memory <byte> .Empty, CancellationToken.None)
                                 .ConfigureAwait(false);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        if (_webSocket.CloseStatus != WebSocketCloseStatus.NormalClosure)
                        {
                            throw new InvalidOperationException($"Websocket closed with error: {_webSocket.CloseStatus}.");
                        }

                        return;
                    }
#endif
                    var memory = _application.Output.GetMemory();
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
                    // Because we checked the CloseStatus from the 0 byte read above, we don't need to check again after reading
                    var receiveResult = await socket.ReceiveAsync(memory, CancellationToken.None)
                                        .ConfigureAwait(false);
#elif NETSTANDARD2_0 || NET461
                    var _ = System.Runtime.InteropServices.MemoryMarshal.TryGetArray <byte>(memory, out var arraySegment);

                    // Exceptions are handled above where the send and receive tasks are being run.
                    var receiveResult = await socket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(false);
#else
#error TFMs need to be updated
#endif
                    // Need to check again for netstandard2.1 because a close can happen between a 0-byte read and the actual read
                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        if (_webSocket.CloseStatus != WebSocketCloseStatus.NormalClosure)
                        {
                            throw new InvalidOperationException($"Websocket closed with error: {_webSocket.CloseStatus}.");
                        }

                        return;
                    }

                    _application.Output.Advance(receiveResult.Count);

                    var flushResult = await _application.Output.FlushAsync().ConfigureAwait(false);

                    // We canceled in the middle of applying back pressure
                    // or if the consumer is done
                    if (flushResult.IsCanceled || flushResult.IsCompleted)
                    {
                        break;
                    }

                    if (!receiveResult.EndOfMessage)
                    {
                        continue;
                    }

                    var readResult = await _transport.Input.ReadAsync().ConfigureAwait(false);

                    // ReSharper disable once ConvertIfStatementToSwitchStatement
                    if (receiveResult.MessageType == WebSocketMessageType.Binary)
                    {
                        DataReceived?.Invoke(readResult.Buffer.ToArray());
                    }
                    else if (receiveResult.MessageType == WebSocketMessageType.Text)
                    {
                        MessageReceived?.Invoke(Encoding.UTF8.GetString(readResult.Buffer.ToArray()));
                    }

                    _transport.Input.AdvanceTo(readResult.Buffer.End);
                }
            }
            catch (OperationCanceledException exception)
            {
                Trace.TraceInformation(exception.Message);
            }
            catch (WebSocketException exception) when
                (exception.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
            {
                Trace.TraceInformation(exception.Message);
            }
            catch (Exception exception)
            {
                if (!_aborted)
                {
                    await _application.Output.CompleteAsync(exception).ConfigureAwait(false);

                    Error?.Invoke(exception);
                }
            }
            finally
            {
                // We're done writing
                await _application.Output.CompleteAsync().ConfigureAwait(false);
            }
        }
コード例 #28
0
        public void Listen(IPAddress ipAddress, int port, ClientConnected clientConnected, DataReceived dataReceived, ErrorOccured errorOccured)
        {
            ListenToIncommingDataResponse response = _transportExecutor.Execute(new ListenToIncommingDataRequest
            {
                IPAddress  = ipAddress,
                Port       = port,
                BufferSize = 2048
            });

            response.ClientConnected += clientConnected;
            response.DataReceived    += dataReceived;
            response.ErrorOccured    += errorOccured;
        }
コード例 #29
0
        public void ReceiveData(MockQueueItem item)
        {
            DataReceivedEventArgs args = new DataReceivedEventArgs(item.ItemData, item.Source, item.Destination, Session);

            DataReceived?.Invoke(this, args);
        }
コード例 #30
0
 protected virtual void OnDataReceived(EventArgs e)
 {
     DataReceived?.Invoke(this, e);
 }
コード例 #31
0
ファイル: Reader.cs プロジェクト: orenbell-nidec/csharp-xbee
 /// <summary>
 /// Programmatic trigger for DataReceived event
 /// </summary>
 /// <param name="message">A message containing the data received</param>
 protected virtual void OnDataReceived(XBeeMessage message)
 {
     DataReceived?.Invoke(this, message);
 }
コード例 #32
0
 protected void initAsyncReader()
 {
     new Action <PipeIPC <T> >((p) => { p.RunAsyncByteReader((b) => { DataReceived?.Invoke(this, b); }); })(this);
 }
コード例 #33
0
        /// <summary>A receive message loop for processing obtained data from the WebSocket.</summary>
        private async void BeginReceive()
        {
            // The clientWebSocket.ReceiveAsync needs a buffer to store the frames coming in.
            byte[] buffer = new byte[BufferSize];

            try
            {
                // This will loop while the ClientWebSocket is still open.
                while (_clientWebSocket.State == WebSocketState.Open)
                {
                    // Frames arrive with partial messages, the FrameReassembler ensures that the messages are appropriately chunked.
                    FrameReassembler frameReassembler = new FrameReassembler();

                    WebSocketReceiveResult result;
                    do
                    {
                        // Ask the ClientWebSocket for any data.
                        result = await _clientWebSocket.ReceiveAsync(new ArraySegment <byte>(buffer), _cancellationTokenSource.Token);

                        switch (result.MessageType)
                        {
                        case WebSocketMessageType.Text:
                            // If we are in the middle of an incomplete message then we need to provide additional frame data.
                            frameReassembler.HandleReceivedData(Encoding.UTF8.GetString(buffer, 0, result.Count));

                            // Does the frameReassembler have any complete messages?
                            while (frameReassembler.HasCompleteMessages())
                            {
                                // Raise an event containing the full message.
                                DataReceived?.Invoke(this, new SubscriptionDataEvent(frameReassembler.GetNextCompleteMessage(), responseTypeMappings));
                            }

                            break;

                        case WebSocketMessageType.Close:
                            // We have been asked to close the socket gracefully.
                            if (_clientWebSocket != null)
                            {
                                await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, _cancellationTokenSource.Token);
                            }

                            // Raise an event.
                            ConnectionStatusChanged?.Invoke(this, ConnectionStatus.DisconnectedByHost);
                            break;

                        default:
                            throw new NotImplementedException(result.MessageType.ToString() + " is not implemented.");
                        }

                        // Although EdgeOS does set the EndOfMessage flag, it lies.
                    } while (_clientWebSocket.State == WebSocketState.Open && (!result.EndOfMessage || frameReassembler.IsMissingData()));
                }
            }
            // EdgeOS non-gracefully closes the socket when a session ends.
            catch (WebSocketException exception)
            {
                if (!exception.Message.Equals("The remote party closed the WebSocket connection without completing the close handshake."))
                {
                    throw;
                }
                ConnectionStatusChanged?.Invoke(this, ConnectionStatus.DisconnectedByHost);
            }
            catch (OperationCanceledException)
            {
                // We cancelled the receive.
            }
            finally
            {
                _clientWebSocket.Dispose();
            }
        }
コード例 #34
0
 protected virtual void OnDataReceived(byte[] data)
 {
     DataReceived?.Invoke(this, data);
 }
コード例 #35
0
        public async Task <bool> CreateConnectionAsync()
        {
            try
            {
                if (connection != null && connection.State == HubConnectionState.Connected)
                {
                    await connection.StopAsync();
                }

                if (socketConnection != null && socketConnection.State == WebSocketState.Open)
                {
                    await socketConnection.CloseAsync(WebSocketCloseStatus.NormalClosure, "", Cts.Token);
                }

                Cts?.Cancel();
                Cts?.Dispose();
                Cts = new CancellationTokenSource();

                _intelliCenterConnection.State = IntelliCenterConnection.ConnectionState.Disconnected;
                OnConnectionChanged();

                if (_settings.ServerURL.StartsWith("http"))
                {
                    var serverUrl = _settings.ServerURL;
                    if (serverUrl.EndsWith("/"))
                    {
                        serverUrl += @"stream/";
                    }
                    else
                    {
                        serverUrl += @"/stream/";
                    }

                    connection = new HubConnectionBuilder()
                                 .WithUrl(serverUrl, options =>
                    {
                        options.AccessTokenProvider       = async() => await CheckCredentials();
                        options.HttpMessageHandlerFactory = (message) =>
                        {
                            if (message is HttpClientHandler clientHandler)
                            {
                                // bypass SSL certificate
                                clientHandler.ServerCertificateCustomValidationCallback +=
                                    (sender, certificate, chain, sslPolicyErrors) => true;
                            }
                            return(message);
                        };
                    })
                                 .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(20) })
                                 .Build();


                    connection.KeepAliveInterval = TimeSpan.FromSeconds(10);

                    connection.Reconnecting += error =>
                    {
                        Debug.Assert(connection.State == HubConnectionState.Reconnecting);
                        _intelliCenterConnection.State = (IntelliCenterConnection.ConnectionState)connection.State;
                        OnConnectionChanged();
                        // Notify users the connection was lost and the client is reconnecting.
                        // Start queuing or dropping messages.

                        return(Task.CompletedTask);
                    };

                    connection.Reconnected += connectionId =>
                    {
                        Debug.Assert(connection.State == HubConnectionState.Connected);
                        _intelliCenterConnection.State = (IntelliCenterConnection.ConnectionState)connection.State;
                        OnConnectionChanged();
                        // Notify users the connection was reestablished.
                        // Start dequeuing messages queued while reconnecting if any.

                        return(Task.CompletedTask);
                    };

                    connection.Closed += error =>
                    {
                        Debug.Assert(connection.State == HubConnectionState.Disconnected);
                        _intelliCenterConnection.State = (IntelliCenterConnection.ConnectionState)connection.State;
                        OnConnectionChanged();
                        // Notify users the connection has been closed or manually try to restart the connection.

                        return(Task.CompletedTask);
                    };

                    await connection.StartAsync(Cts.Token);

                    if (connection.State == HubConnectionState.Connected)
                    {
                        DataSubscribe();
                    }

                    _intelliCenterConnection.State = (IntelliCenterConnection.ConnectionState)connection.State;

                    OnConnectionChanged();
                }
                else if (_settings.ServerURL.StartsWith("ws"))
                {
                    socketConnection = new ClientWebSocket();

                    await socketConnection.ConnectAsync(new Uri(_settings.ServerURL), Cts.Token);

                    Thread.Sleep(50);

                    if (socketConnection.State == WebSocketState.Open)
                    {
                        DataSubscribe();
                    }

                    switch (socketConnection.State)
                    {
                    case WebSocketState.Aborted:
                    case WebSocketState.Closed:
                    case WebSocketState.CloseReceived:
                    case WebSocketState.CloseSent:
                    case WebSocketState.None:
                        _intelliCenterConnection.State = IntelliCenterConnection.ConnectionState.Disconnected;
                        break;

                    case WebSocketState.Connecting:
                        _intelliCenterConnection.State = IntelliCenterConnection.ConnectionState.Connecting;
                        break;

                    case WebSocketState.Open:
                        _intelliCenterConnection.State = IntelliCenterConnection.ConnectionState.Connected;
                        break;

                    default:
                        _intelliCenterConnection.State = IntelliCenterConnection.ConnectionState.Disconnected;
                        break;
                    }

                    OnConnectionChanged();
                }
            }
            catch (Exception ex)
            {
                //Debug.WriteLine(ex);
                if (ex.Message.Contains("Unauthorized"))
                {
                    DataReceived?.Invoke(this, "Unauthorized");
                }
                //this._logService.LogError(ex.ToString());
                //this._cloudLogService.LogError(ex);
            }



            return(await Task.FromResult(_intelliCenterConnection.State != IntelliCenterConnection.ConnectionState.Disconnected));
        }