示例#1
0
        /// <summary>
        /// Метод, вызывающийся при завершении чтения
        /// </summary>
        /// <param name="ar"></param>
        private void OnCompleteSocketReceive(IAsyncResult ar)
        {
            //если сокет уже отключили, то просто выходим
            if (!_attached || _socket == null)
            {
                return;
            }

            SocketError socketError;
            int         length;

            try
            {
                //получаем количество прочитанных байт
                length = _socket.EndReceive(ar, out socketError);
            }
            catch (Exception e)
            {
                DoDisconnect(e);
                return;
            }

            //Проверяем на ошибки при чтении сокета
            if (socketError != SocketError.Success || length <= 0)
            {
                DoDisconnect(new Exception(socketError.ToString()));
                return;
            }

            _offset += length;//устанавливаем текущую длину данных

            //генерируем событие и отправляем его на вычетку
            var receiveEvent = new SocketReceiveEventArgs(this, _readCommandBuffer, _offset);

            try
            {
                AfterReceive?.Invoke(this, receiveEvent);
            }
            catch (Exception e)
            {
                //вычитка не получилась
                DoDisconnect(e);
                return;
            }

            //Проверяем, сколько удалось прочитать из буфера данных
            if (receiveEvent.FinishIndex > 0)
            {
                //устанавливаем новое семещение
                _offset = receiveEvent.Length - receiveEvent.FinishIndex;
                for (var i = 0; i < _offset; ++i)
                {
                    //переносим данные по новому смещению
                    _readCommandBuffer[i] = _readCommandBuffer[i + receiveEvent.FinishIndex];
                }
            }

            //повторяем процедуру чтения данных на сокете
            DoSocketReceive();
        }
示例#2
0
 public static void UnregisterScannerActivity()
 {
     try
     {
         ElContext?.UnregisterReceiver(Receiver);
     }
     catch { }
     AfterReceive?.GetInvocationList().ToList().ForEach(x => AfterReceive   -= (EventHandler <ReceiveEventArgs>)x);
     BeforeReceive?.GetInvocationList().ToList().ForEach(x => BeforeReceive -= (EventHandler)x);
     ElContext = null;
     ARP       = null;
 }
示例#3
0
            //public string ReceivedData { get; set; }
            //public event EventHandler AfterReceive;
            //public event EventHandler BeforeReceive;
            public override void OnReceive(Context context, Intent intent)
            {
                try
                {
                    if (IsBusy)
                    {
                        return;
                    }
                    IsBusy = true;
                    BeforeReceive?.Invoke(context, new EventArgs());

                    string _scanAll = cDataWedge.HandleDecodeData(intent);
                    string _pattern = @"(.*)\|(Scanner|MSR)\|(.*)\|(\d+)";
                    var    _matches = Regex.Match(_scanAll, _pattern);
                    string _scan    = _matches.Groups[1].ToString();
                    try
                    {
                        AfterReceive?.Invoke(context, new ReceiveEventArgs()
                        {
                            ReceivedData = _scan, Silent = silent
                        });
                    } catch (Exception ex)
                    {
                        if (!silent)
                        {
                            cSounds.Error(context);
                        }
                        Toast.MakeText(context, string.Format("Error in postprocess: {0}", ex.Message), ToastLength.Long).Show();
                        _scan  = "";
                        IsBusy = false;
                        return;
                    }
                    if (_scan == "")
                    {
                        if (!silent)
                        {
                            cSounds.Error(context);
                        }
                        Toast.MakeText(context, "Please enter valid data", ToastLength.Long).Show();
                        IsBusy = false;
                        return;
                    }

                    IsBusy = false;
                }
                catch //(Exception ex)
                {
                    IsBusy = false;
                }
            }
示例#4
0
 private void DoCommandProcess(IRoomCommand command)
 {
     try
     {
         //возбуждаем событие приема команды
         AfterReceive?.Invoke(this, command);
     }
     catch (Exception e)
     {
         LogException(e);
     }
     finally
     {
         //отправляем команду обратно в пул на переиспользование
         _poolCommand.Free(command);
     }
 }
示例#5
0
        public void StartClient(string message, AfterReceive ar)
        {
            // Connect to a remote device.
            try
            {
                afterReceive = ar;

                receiveDone = new ManualResetEvent(false);

                int port = SocketConstants.port;

                IPAddress  ipAddress = IPAddress.Parse(DepartmentQueue.GetLocalIPAddress());
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket client = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback), client);
                //connectDone.WaitOne();

                // Send test data to the remote device.
                Send(client, $"{message} <EOF>");
                //sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                Console.WriteLine("Closed socket");

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
示例#6
0
        public void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                Tuple <byte[], Socket> tuple = (Tuple <byte[], Socket>)ar.AsyncState;
                byte[] buffer = tuple.Item1;
                Socket client = tuple.Item2;

                // 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.

                    sb.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));

                    // Get the rest of the data.
                    client.BeginReceive(buffer, 0, SocketConstants.BUFFER_SIZE, 0,
                                        new AsyncCallback(ReceiveCallback), new Tuple <byte[], Socket>(buffer, client));
                }
                else
                {
                    string content = sb.ToString();
                    content = content.Replace(SocketConstants.EOF, "");
                    content = content.Trim();

                    // All the data has arrived; clear.
                    sb.Clear();

                    if (content.StartsWith(SocketConstants.SECONDARYTICKETS))
                    {
                        content = content.Replace(SocketConstants.SECONDARYTICKETS, "");
                        content = content.Trim();

                        List <SecondaryTicket> receivedTickets = Newtonsoft.Json.JsonConvert.DeserializeObject <List <SecondaryTicket> >(content);

                        // Update existing SecondaryTickets and add new ones
                        for (int i = 0; i < receivedTickets.Count; i++)
                        {
                            SecondaryTicket newTicket = receivedTickets[i];
                            int             index     = secondaryTickets.FindIndex((x) => x.Id == newTicket.Id);

                            if (index == -1)
                            {
                                secondaryTickets.Add(newTicket);
                            }
                            else
                            {
                                secondaryTickets[index] = newTicket;
                            }
                        }

                        UpdateSecondaryTicketsFile();
                    }

                    if (content.StartsWith(SocketConstants.OK))
                    {
                    }

                    if (afterReceive != null)
                    {
                        afterReceive();
                        afterReceive = null;
                    }

                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
示例#7
0
 protected virtual bool Response(Message message)
 {
     AfterReceive?.Invoke(this, new LinkEventArgs(message));
     return(false);
 }