Beispiel #1
0
        private void callback(IAsyncResult ar)
        {
            try
            {
                sck.EndReceive(ar);
                var buf = new byte[8192];
                var rec = sck.Receive(buf, buf.Length, 0);

                if (rec < buf.Length)
                {
                    Array.Resize(ref buf, rec);
                }

                Received?.Invoke(this, buf);

                sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Close();

                Disconnected?.Invoke(this);
            }
        }
Beispiel #2
0
        private void OnReceive(HostMask prefix, string command, string[] args)
        {
            _logger.Log(LogLevel.Debug, _plugin.Name, "OnReceive - {0}, {1}, {2}", prefix.Mask, command, args);

            if (Received != null)
            {
                IrcEventArgs e = new IrcEventArgs(prefix, command, args);
                Received.Invoke(this, e);
                if (e.Handled)
                {
                    return;
                }
            }

            switch (command)
            {
            case "NICK": OnNick(prefix, args); break;

            case "PING": OnPing(args); break;

            case "001": OnWelcome(args); break;

            case "002": OnYourHost(args); break;

            case "003": OnCreated(args); break;

            case "004": OnMyInfo(args); break;
            }
        }
Beispiel #3
0
        private void OnReceive(Packet pk, IPEndPoint remote)
        {
            var e = new ReceivedEventArgs(pk);

            e.UserState = remote;

            LastTime = DateTime.Now;
            //if (StatReceive != null) StatReceive.Increment(e.Length);

            if (Log.Enable && LogReceive)
            {
                WriteLog("Recv [{0}]: {1}", e.Length, e.ToHex(32, null));
            }

            Received?.Invoke(this, e);

            if (Packet != null && e.Packet != null && MessageReceived != null)
            {
                var msg = Packet.LoadMessage(e.Packet);
                var me  = new MessageEventArgs
                {
                    Packet    = e.Packet,
                    UserState = e.UserState,
                    Message   = msg
                };
                MessageReceived(this, me);
            }
        }
        private async void ListenForMessages(WebSocket socket)
        {
TOP:
            try
            {
                if (!socket.IsConnected)
                {
                    return;
                }

                var message = await socket.ReadMessageAsync(_tokenSource.Token);

                if (message != null)
                {
                    using (var ms = new MemoryStream())                     // length was throwing an exception
                    {
                        message.CopyTo(ms);
                        var segment = new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length);
                        var args    = new DataReceivedArgs {
                            Data = segment, SessionID = socket
                        };
                        Received.Invoke(this, args);
                    }
                }
                goto TOP;
            }
            catch (TaskCanceledException) { }
            catch (Exception)
            {
                goto TOP;
            }
        }
Beispiel #5
0
 private async Task ReceiveLoopAsync(CancellationToken token)
 {
     try
     {
         while (!token.IsCancellationRequested)
         {
             while (await _receivedMessages.In.WaitToReadAsync(token))
             {
                 while (_receivedMessages.In.TryRead(out var message))
                 {
                     await Received?.Invoke(message);
                 }
             }
         }
         Closed?.Invoke(null);
     }
     catch (OperationCanceledException)
     {
         // Do nothing, we were just asked to shut down.
         Closed?.Invoke(null);
     }
     catch (Exception ex)
     {
         Closed?.Invoke(ex);
     }
 }
Beispiel #6
0
 public void OnReceived(string msg)
 {
     if (this.bConnect)
     {
         Received?.Invoke(this, msg);
     }
 }
Beispiel #7
0
        private void ReceivedCallback(IAsyncResult ar)
        {
            try
            {
                socket.EndReceive(ar);

                byte[] buffer  = new byte[1024];
                int    receive = socket.Receive(buffer, buffer.Length, 0);

                if (receive < buffer.Length)
                {
                    Array.Resize(ref buffer, receive);
                }

                Received?.Invoke(this, buffer);

                socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, ReceivedCallback, null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Client connection error: " + e.Message);
                Close();

                Disconnected?.Invoke(this);
            }
        }
 private void ReceiveCallback(IAsyncResult ar)
 {
     try {
         // Retrieve the state object and the client socket
         // from the asynchronous state object.
         StateObject state = (StateObject)ar.AsyncState;
         Client = state.workSocket;
         // Read data from the remote device.
         int bytesRead = Client.EndReceive(ar);
         if (bytesRead > 0)
         {
             // There might be more data, so store the data received so far.
             state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
         }
         if (bytesRead < state.BufferSize)
         {
             //  Get the rest of the data.
             Client.BeginReceive(state.buffer, 0, state.BufferSize, 0,
                                 ReceiveCallback, state);
         }
         else
         {
             // All the data has arrived; put it in response.
             if (state.sb.Length >= state.BufferSize)
             {
                 Received?.Invoke(this, state.sb.ToString());
             }
         }
     } catch (Exception e) {
         ErrorAccrued?.Invoke(this, new ErrorEventArgs(e));
     }
 }
Beispiel #9
0
 public void OnReceived(byte[] data)
 {
     if (Received != null)
     {
         Received.Invoke(data);
     }
 }
Beispiel #10
0
        public void SubscribeCommands <TMessage>(IContainer container)
        {
            var receiverType = ResolveReceiverType <TMessage>(container);

            var topic      = typeof(TMessage).Name;
            var routingKey = $"{Namespace}.{topic}";

            var channel = CommandQueueDeclare(routingKey);

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += (o, ea) =>
            {
                var json = ea.Body.ToContent();
                Received?.Invoke(this, new ReceivedEventArgs
                {
                    Topic     = topic,
                    HandledBy = receiverType,
                    Message   = json
                });

                Handle(container, json.ToObject <TMessage>());
                Channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
            };

            channel.BasicConsume(queue: routingKey,
                                 noAck: false,
                                 consumer: consumer);
        }
Beispiel #11
0
 internal virtual void MessageReceived(MessageResponse response)
 {
     foreach (JToken message in response.Messages)
     {
         Received?.Invoke(message.ToObject <string>());
     }
 }
Beispiel #12
0
        public void SubscribeEvents <TMessage>(IContainer container)
        {
            var receiverType = ResolveReceiverType <TMessage>(container);

            var topic     = typeof(TMessage).Name;
            var queueName = Channel.QueueDeclare().QueueName;

            Channel.QueueBind(queue: queueName,
                              exchange: Namespace,
                              routingKey: topic);

            var consumer = new EventingBasicConsumer(Channel);

            consumer.Received += (o, e) =>
            {
                var json = e.Body.ToContent();
                Received?.Invoke(this, new ReceivedEventArgs
                {
                    Topic     = topic,
                    HandledBy = receiverType,
                    Message   = json
                });

                Handle(container, json.ToObject <TMessage>());
            };

            Channel.BasicConsume(queue: queueName,
                                 noAck: false,
                                 consumer: consumer);
        }
 public SerialPortDownloader(SerialPortHelper portHelper)
 {
     _portHelper = portHelper;
     _portHelper.DataReceived += (sender, e) =>
     {
         var port = sender as SerialPort;
         if (port == null)
         {
             return;
         }
         var readBytes = new List <byte>();
         lock (_buffer)
         {
             while (port.BytesToRead > 0)
             {
                 readBytes.Add((byte)port.ReadByte());
             }
             _buffer.AddRange(readBytes);
         }
         var package = DecodePackage();
         Received?.Invoke(new DownloadSenderReceivedArgs
         {
             ReceiveContent = readBytes.ToArray(),
             Package        = package
         });
     };
 }
        private void ErrorMessage(Exception ex)
        {
            WriteLog(ex);
            FormCollection frms = Application.OpenForms;

            for (int i = 0; i < frms.Count; i++)
            {
                if (frms[i] == null)
                {
                    i++;
                    continue;
                }
                if (frms[i] is PopMain)
                {
                    PopMain pop = (PopMain)frms[i];
                    // 해당 POP의 라인아이디와 같은 경우
                    if (pop.WorkerInfo.LineID == LineID)
                    {
                        ReceiveEventArgs e = new ReceiveEventArgs();
                        e.Message     = string.Join("오류", ex.Message);
                        e.LineID      = LineID;
                        e.IsCompleted = false;

                        if (!pop.IsDisposed)
                        {
                            if (Received != null)
                            {
                                Received.Invoke(this, e);
                            }
                        }
                    }
                }
            }
        }
        private async Task ReceiveLoop(WebSocket webSocket, CancellationToken cancellationToken)
        {
            var buffer = new byte[MaxMessageSize];

            while (true)
            {
                var result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), cancellationToken);

                if (result == null)
                {
                    break;
                }

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    break;
                }

                var data = await ReadFrames(result, webSocket, buffer);

                if (data.Count == 0)
                {
                    break;
                }

                try
                {
                    Received?.Invoke(data);
                }
                catch (Exception e)
                {
                    ReceivedError?.Invoke(e);
                }
            }
        }
        public override void HandleBasicDeliver(
            string consumerTag,
            ulong deliveryTag,
            bool redelivered,
            string exchange,
            string routingKey,
            IBasicProperties properties,
            byte[] body)
        {
            base.HandleBasicDeliver(consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body);

            if (Received == null)
            {
                return;
            }

            try
            {
                var receivedMessage = ParseMessage(properties, body);

                Received?.Invoke(
                    this,
                    new MottattMeldingArgs(receivedMessage, new SvarSender(_sendHandler, receivedMessage, () => Model.BasicAck(deliveryTag, false))));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #17
0
        public async Task ReceiveAsync()
        {
            _cts = new CancellationTokenSource();
            var w = new ClientWebSocket();

            _ws = w;
            await w.ConnectAsync(new Uri(_url), _cts.Token);

            Opened?.Invoke(this, EventArgs.Empty);
            while (true)
            {
                WebSocketReceiveResult result;
                try
                {
                    result = await w.ReceiveAsync(new ArraySegment <byte>(buf), _cts.Token);
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                if (IsClosing(result.CloseStatus))
                {
                    break;
                }
                if (result.MessageType == WebSocketMessageType.Text && result.EndOfMessage)
                {
                    var s = Encoding.UTF8.GetString(buf, 0, result.Count);
                    Received?.Invoke(this, s);
                }
            }
            _cts = null;
        }
Beispiel #18
0
        private void Receive(IAsyncResult AR)
        {
            Socket serverSocket = (Socket)AR.AsyncState;
            int    received;

            try
            {
                received = serverSocket.EndReceive(AR);

                byte[] recBuf = new byte[received];
                Array.Copy(buffer, recBuf, received);
                string data = Encoding.ASCII.GetString(recBuf);

                Received?.Invoke(data);

                socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, Receive, socket);
            }
            catch (Exception)
            {
                serverSocket.Close();

                Log?.Invoke("Client disconnected");

                return;
            }
        }
Beispiel #19
0
 private void OnReceived(IAsyncResult ar)
 {
     try
     {
         int bytesRead = socket.EndReceive(ar);
         if (bytesRead > 0)
         {
             if (enableMultiBytes)
             {
                 queue.Write(buffer, 0, bytesRead);
                 Array.Clear(buffer, 0, bytesRead);
                 GetPacket();
             }
             else
             {
                 byte[] data = new byte[bytesRead];
                 Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                 Array.Clear(buffer, 0, bytesRead);
                 socket.BeginReceive(buffer, 0, buffersize, 0, new AsyncCallback(OnReceived), null);
                 Received?.Invoke(this, bytesRead, data);
             }
         }
         else
         {
             Close();
         }
     }
     catch (Exception e)
     {
         if (e is Win32Exception w && w.ErrorCode == 10054)
         {
             Disconnected?.Invoke(this);
         }
Beispiel #20
0
        /* ----------------------------------------------------------------- */
        ///
        /// RssSubscriber
        ///
        /// <summary>
        /// オブジェクトを初期化します。
        /// </summary>
        ///
        /// <param name="context">同期用オブジェクト</param>
        ///
        /* ----------------------------------------------------------------- */
        public RssSubscriber(SynchronizationContext context)
        {
            _dispose = new OnceAction <bool>(Dispose);
            _context = context;

            _tree = new BindableCollection <IRssEntry> {
                Context = context
            };
            _tree.CollectionChanged += (s, e) =>
            {
                AutoSaveCore();
                CollectionChanged?.Invoke(this, e);
            };

            _monitors[0] = new RssMonitor {
                Interval = TimeSpan.FromHours(1)
            };
            _monitors[0].Subscribe(e => Received?.Invoke(this, ValueEventArgs.Create(e)));

            _monitors[1] = new RssMonitor {
                Interval = TimeSpan.FromHours(24)
            };
            _monitors[1].Subscribe(e => Received?.Invoke(this, ValueEventArgs.Create(e)));

            _monitors[2] = new RssMonitor(); // for RssCheckFrequency.None
            _monitors[2].Subscribe(e => Received?.Invoke(this, ValueEventArgs.Create(e)));

            _autosaver.AutoReset = false;
            _autosaver.Interval  = 1000.0;
            _autosaver.Elapsed  += WhenAutoSaved;
        }
Beispiel #21
0
 ///<summary>
 /// Invoked when a delivery arrives for the consumer.
 /// </summary>
 /// <remarks>
 /// Handlers must copy or fully use delivery body before returning.
 /// Accessing the body at a later point is unsafe as its memory can
 /// be already released.
 /// </remarks>
 public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, ReadOnlyMemory <byte> body)
 {
     base.HandleBasicDeliver(consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body);
     Received?.Invoke(
         this,
         new BasicDeliverEventArgs(consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body));
 }
        private void HandleReceivedLetter(ILetter receivedLetter, AckState ackState)
        {
            switch (receivedLetter.Type)
            {
            case LetterType.Initialize:
                RemoteNodeId = new Guid(receivedLetter.Parts[0]);
                HandleInitialize();
                break;

            case LetterType.Shutdown:
                _remoteShutdownRequested = true;
                ChannelDisconnecting?.Invoke(this, ShutdownReason.Remote);
                break;

            case LetterType.User:
                Received?.Invoke(receivedLetter, CreateReceivedEventArgs(ackState));
                break;

            case LetterType.Batch:
                for (var i = 0; i < receivedLetter.Parts.Length; i++)
                {
                    var batchedLetter = _letterDeserializer.Deserialize(receivedLetter.Parts[i]);
                    Received?.Invoke(batchedLetter, CreateReceivedEventArgs(ackState));
                }
                break;
            }
        }
Beispiel #23
0
        private void OnReceive(HostMask prefix, string command, string[] args)
        {
            if (Received != null)
            {
                IrcEventArgs e = new IrcEventArgs(prefix, command, args);
                Received.Invoke(this, e);
                if (e.Handled)
                {
                    return;
                }
            }

            switch (command)
            {
            case "NICK": OnNick(prefix, args); break;

            case "PING": OnPing(args); break;

            case "001": OnWelcome(args); break;

            case "002": OnYourHost(args); break;

            case "003": OnCreated(args); break;

            case "004": OnMyInfo(args); break;
            }
        }
Beispiel #24
0
            internal override void OnReceivedEvent(Parcel parcel)
            {
                string param1 = parcel.ReadString();
                Bundle param2 = parcel.ReadBundle();

                Received?.Invoke(param1, param2);
            }
        private void StartReceive()
        {
            Task.Run(async() =>
            {
                while (_udpClient != null)
                {
                    try
                    {
                        UdpReceiveResult res = await _udpClient.ReceiveAsync();

                        Transmission msg = new Transmission(res.Buffer, Transmission.EType.Received);
                        msg.Origin       = res.RemoteEndPoint;
                        msg.Destination  = _udpClient.Client.LocalEndPoint as IPEndPoint;

                        Received?.Invoke(this, new ReceivedEventArgs(msg));
                    }
                    catch (SocketException ex)
                    {
                        // Ignore this error, triggered after sending
                        // a packet to an unreachable port. UDP is not
                        // reliable anyway, this can safetly be ignored.
                        if (ex.ErrorCode != 10054)
                        {
                            Leave();
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        Leave();
                        break; // end receive;
                    }
                }
            });
        }
        /// <inheritdoc cref="ISocketAdapter.Connect"/>
        public void Connect(Uri uri, int timeout)
        {
            // TODO will need to use window.setTimeout to implement timeouts on DOM WebSocket.
            if (Ref > -1)
            {
                ReceivedError?.Invoke(new SocketException((int)SocketError.IsConnected));
                return;
            }

            _uri         = uri;
            IsConnecting = true;

            Action open = () =>
            {
                IsConnected  = true;
                IsConnecting = false;
                Connected?.Invoke();
            };
            Action <int, string> close = (code, reason) =>
            {
                IsConnected  = false;
                IsConnecting = false;
                Ref          = -1;
                Closed?.Invoke();
            };
            Action <string> error = reason =>
            {
                IsConnected = false;
                Ref         = -1;
                ReceivedError?.Invoke(new Exception(reason));
            };
            Action <string> handler = message => { Received?.Invoke(new ArraySegment <byte>(Encoding.UTF8.GetBytes(message))); };

            Ref = UnityWebGLSocketBridge.Instance.CreateSocket(uri.AbsoluteUri, open, close, error, handler);
        }
Beispiel #27
0
        internal async void StartAsync()
        {
            lock (_lockObject)
            {
                _udpClient = new UdpClient(_port);
                _udpTokenSource?.Cancel();
                _udpTokenSource = new CancellationTokenSource();
            }

            var token = _udpTokenSource.Token;

            while (!token.IsCancellationRequested)
            {
                var receivedResult = _udpClient != null
                    ? await _udpClient.ReceiveAsync().ConfigureAwait(false)
                    : default(UdpReceiveResult);

                var bytes = receivedResult.Buffer;

                if (!token.IsCancellationRequested &&
                    bytes != null &&
                    bytes.Any())
                {
                    var message = Encoding.ASCII.GetString(bytes);
                    Received?.Invoke(message);
                }
            }
        }
        private void ConnectDisconnect()
        {
            if (_port != null && _port.IsOpen)
            {
                _port.Close();
                _port.Dispose();
                _nmea.Dispose();

                _port = null;
                _nmea = null;

                ButtonText = "Connect";
                StatusText = "Not Connected.";
            }
            else
            {
                try
                {
                    _port = new SerialPort(Port, Baud);
                    _port.Open();
                    _nmea = new StreamDevice(_port.BaseStream);
                    _nmea.OpenAsync().Wait();

                    _nmea.MessageReceived += (sender, args) => { Received?.Invoke(sender, args); };
                    ButtonText             = "Disconnect";
                    StatusText             = $"Connected to {Port}";
                }
                catch (Exception e)
                {
                    StatusText = $"Not connected: {e.GetType()}";
                    _port      = null;
                    _nmea      = null;
                }
            }
        }
        private void EndOrContinueRead(IAsyncResult ar)
        {
            ReadIOState state = ar.AsyncState as ReadIOState;

            // Get the number of bytes read and advance position by the same amount
            try
            {
                int bytesRead = networkStream.EndRead(ar);
                if (bytesRead > 0)
                {
                    state.AdvancePosition(bytesRead);
                }
            }
            catch (Exception ex)
            {
                Received.Invoke(this, new ReceivedEventArgs(ex, this, state.Data));
            }

            if (state.Remaining > 0)
            {
                Read(state);
            }
            else if (state.LengthRead)
            {
                int length = BitConverter.ToInt32(state.Data, 0);
                Read(new ReadIOState(length, true, false));
            }
            else
            {
                Received?.Invoke(this, new ReceivedEventArgs(this, state.Data));
                Read(new ReadIOState(4, false, true));
            }
        }
Beispiel #30
0
        private async Task ReceiveMessage()
        {
            var result = _innerConsumer.Consume(_cancellationTokenSource.Token);

            if (result == null)
            {
                return;
            }

            if (result.IsPartitionEOF)
            {
                _logger.LogInformation("Partition EOF reached: {topic} {partition} @{offset}", result.Topic,
                                       result.Partition,
                                       result.Offset);
                return;
            }

            _consumedAtLeastOnce = true;
            _logger.LogTrace("Consuming message: {topic} {partition} @{offset}", result.Topic, result.Partition,
                             result.Offset);

            if (Received != null)
            {
                await Received.Invoke(result.Message, result.TopicPartitionOffset);
            }
        }