/// <summary>
        /// Handle clients
        /// </summary>
        /// <param name="c">TcpClient as object</param>
        private void HandleClient(object c)
        {
            TcpClient client = (TcpClient)c;

            while (true)
            {
                try
                {
                    Packet receivePacket = client.Receive();
                    if (OnReceiveData != null)
                    {
                        OnReceiveData.Invoke(client, receivePacket);
                    }
                }
                catch
                {
                    break;
                }
            }

            tcpClients.Remove(client);

            if (OnPlayerDisconnect != null)
            {
                OnPlayerDisconnect.Invoke(client);
            }

            client.Close();
        }
Exemplo n.º 2
0
        public override void Add(byte[] data, int offset = 0, int length = -1)
        {
            length = length < 0 ? data.Length : length;
            try
            {
                if (_IsFirst)
                {
                    var first = Encoding.UTF8.GetString(data.Take(length).ToArray());
                    if (first.Contains("No such file or directory") || first.Contains("Permission denied"))
                    {
                        throw new Exception(first);
                    }
                    _IsFirst = false;

                    fileInfo = new FileInfo(LocalFile);
                    fos      = new FileStream(fileInfo.FullName, FileMode.Create, FileAccess.Write);
                }
                //data处理
                data   = ConvertToLinuxData(data, length);
                length = data.Length;
                fos.Write(data, 0, length);
                //receive event
                OnReceiveData?.Invoke(data, 0, length);
            }
            catch (IOException e)
            {
                throw new ApplicationException("Cat to file: Writing local file failed!", e);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// A callback triggered by receiving data from the server.
        /// </summary>
        /// <param name="asyn">The packet object received from the server containing the received message.</param>
        private void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                Packet socketData = (Packet)asyn.AsyncState;
                int    dataSize   = socketData.CurrentSocket.EndReceive(asyn);

                OnReceiveData?.Invoke(socketData.DataBuffer, dataSize);

                WaitForData();
            }

            catch (ObjectDisposedException)
            {
                System.Console.WriteLine("Client EXCEPTION in OnDataReceived: Socket has been closed");
            }

            catch (SocketException se)
            {
                System.Console.WriteLine("Client EXCEPTION in OnDataReceived: " + se.Message);

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

                ToFile(se.Message);
            }
        }
Exemplo n.º 4
0
        private void RecThreadTask()
        {
            try
            {
                while (!m_Terminate)
                {
                    if (m_Socket.Connected)
                    {
                        int byteCount = 0;
                        try
                        {
                            byteCount = m_Socket.Receive(m_Buffer);
                        }
                        catch (Exception e)
                        {
                            Trace(EventType.Error,
                                  "Receiving socket data, connection will be closed: {0}",
                                  ConnID);
                            Trace(e);
                            OnReceiveError?.Invoke(this, e);
                        }

                        if (byteCount > 0)
                        {
                            byte[] data = new byte[byteCount];
                            Array.Copy(m_Buffer, data, byteCount);
                            Trace(EventType.Full,
                                  "Received socket data. ConnID: {0} Length: {1} byte(s)",
                                  ConnID,
                                  byteCount);
                            OnReceiveData?.Invoke(this, data);
                        }
                        else
                        {
                            Trace(EventType.Full,
                                  "Closing socket connection (from the other side!). ConnID: {0}",
                                  ConnID);
                            Close();
                        }
                    }
                    else
                    {
                        Trace(EventType.Full,
                              "Closing socket connection (!Connected). ConnID: {0}",
                              ConnID);
                        Close();
                    }
                }
                Trace(EventType.Full,
                      "Finished receiving thread. ConnID: {0}",
                      ConnID);
            }
            catch (Exception exc)
            {
                Trace(exc);
            }
        }
 private void ReadClientsStream()
 {
     foreach (var item in SocketClients)
     {
         int result = item.Value.ReadStream();
         if (result == -1)
         {
         }
         else if (result == -2)
         {
         }
         else
         {
             OnReceiveData?.Invoke(item.Key, item.Value.ReadBuffer, result);
         }
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// 执行数据接收
        /// </summary>
        /// <param name="socket">数据接收的端口</param>
        public bool DoReceive(Socket socket)
        {
            //read check result
            byte[] pullResult = new byte[8];
            AdbSocketHelper.Read(socket, pullResult);

            if (!CheckPullFileResult(pullResult))
            {
                return(false);
            }

            byte[]     data = new byte[BufferSize];
            FileInfo   f    = new FileInfo(_Local);
            FileStream fos  = fos = new FileStream(f.FullName, System.IO.FileMode.Create, FileAccess.Write);

            using (fos)
            {
                while (true)
                {
                    if (AdbSocketHelper.CheckResult(pullResult, Encoding.Default.GetBytes("DONE")))
                    {
                        break;
                    }
                    if (AdbSocketHelper.CheckResult(pullResult, Encoding.Default.GetBytes("DATA")) == false)
                    {
                        return(false);
                    }
                    //get an check buffer length
                    int length = ArrayHelper.Swap32bitFromArray(pullResult, 4);
                    if (length > 64 * 1024)
                    {
                        throw new ApplicationException("Receiving too much data.");
                    }
                    //read data
                    AdbSocketHelper.Read(socket, data, length);
                    AdbSocketHelper.Read(socket, pullResult);
                    //write file
                    try
                    {
                        fos.Write(data, 0, length);
                    }
                    catch (IOException e)
                    {
                        throw new ApplicationException("Writing local file failed!", e);
                    }
                    //receive event
                    OnReceiveData?.Invoke(data, 0, length);
                }
                //flush
                try
                {
                    fos.Flush();
                    //设置文件的原始创建时间
                    //File.SetCreationTime(f.FullName,);
                }
                catch (IOException e)
                {
                    throw new ApplicationException("Writing local file failed!", e);
                }
            }

            return(true);
        }
Exemplo n.º 7
0
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            IDataItem dataItem = GenerateNextValue();

            OnReceiveData?.Invoke(dataItem.Y, new DateTime((long)dataItem.X * TimeSpan.TicksPerMillisecond));
        }
        // TODO: Convert to Memory<byte> from byte[]
        private void ParseAndProcessReceivedPacket(byte[] receivedMsg, CancellationToken cancellationToken)
        {
            try
            {
                var processor = _receiveMessageFactoryManager.CreateProcessor(receivedMsg);
                if (processor == null)
                {
                    return;
                }

                if (processor.Execute(receivedMsg))
                {
                    var requestType    = (HcomHostRequestType)processor.RequestType;
                    var responseString = processor.ToString();
                    _logger.LogTrace("Received message {messageType}, Content: {messageContent}", requestType, responseString);
                    switch (requestType)
                    {
                    case HcomHostRequestType.HCOM_HOST_REQUEST_UNDEFINED_REQUEST:
                        break;

                    // This set are responses to request issued by this application
                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_REJECTED:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.Data, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_ACCEPTED:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.Accepted));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_CONCLUDED:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.Concluded));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_ERROR:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.Data, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_INFORMATION:
                        _logger.LogInformation("Meadow StdInfo: {message}", responseString);
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.Data, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_LIST_HEADER:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.FileListTitle, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_LIST_MEMBER:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.FileListMember, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_CRC_MEMBER:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.FileListCrcMember, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_MONO_STDOUT:
                        _logger.LogInformation("Meadow StdOut: {message}", responseString);
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.AppOutput, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_MONO_STDERR:
                        _logger.LogWarning("Meadow StdErr: {message}", responseString);
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.ErrOutput, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_DEVICE_INFO:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.DeviceInfo, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_TRACE_MSG:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.MeadowTrace, responseString));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_TEXT_RECONNECT:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.SerialReconnect));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_DEBUGGING_MONO_DATA:
                        DebuggerMessages.Add(processor.MessageData !, cancellationToken);
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_FILE_START_OKAY:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.DownloadStartOkay));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_FILE_START_FAIL:
                        OnReceiveData?.Invoke(this, new MeadowMessageEventArgs(MeadowMessageType.DownloadStartFail));
                        break;

                    case HcomHostRequestType.HCOM_HOST_REQUEST_GET_INITIAL_FILE_BYTES:
                    {
                        var msg = System.Text.Encoding.UTF8.GetString(processor.MessageData);

                        OnReceiveData?.Invoke(
                            this,
                            new MeadowMessageEventArgs(MeadowMessageType.InitialFileData, msg));

                        break;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex, "An error occurred parsing a received packet");
            }
        }
Exemplo n.º 9
0
 private void SocketConn_ReceiveData(SocketConn scktConn, byte[] data)
 {
     OnReceiveData?.Invoke(data);
 }
Exemplo n.º 10
0
        private void MessageFactory(CommandEtherNetIPHeader header, byte[] bodyBytes)
        {
            try
            {
                Trace(EventType.Full, string.Format("{0} - Receive msg. '{1}'", LOG_TAG, header.Command));
                long headerSize = Marshal.SizeOf(typeof(CommandEtherNetIPHeader));
                switch (header.Command)
                {
                case EncapsulationCommands.ListServices:
                {
                    if (bodyBytes.Length == 0)
                    {
                        MsgListServiceReply msg = new MsgListServiceReply();
                        msg.CommandSpecificDataListServices           = new CommandSpecificDataListServices();
                        msg.CommandSpecificDataListServices.ItemCount = 1;
                        msg.CommandSpecificDataListServices.Items     = new CommandSpecificDataListServicesItem[1];
                        msg.CommandSpecificDataListServices.Items[0]  = new CommandSpecificDataListServicesItem
                        {
                            TypeCode        = CommonPacketItemID.ListServicesResponse,
                            Version         = 1,
                            CapabilityFlags = Convert.ToUInt16("100100000", 2),
                            ServiceName     = Encoding.ASCII.GetBytes("Communications\0\0")
                        };
                        header.Length = msg.SizeOf();
                        msg.CommandSpecificDataListServices.Items[0].Length =
                            (ushort)(msg.CommandSpecificDataListServices.Items[0].SizeOf() - 2 - 2);
                        SendMessage(header, msg);
                    }
                    break;
                }

                case EncapsulationCommands.RegisterSession:
                {
                    int pointer = 0;
                    CommandSpecificDataRegisterSession cmdSpecData =
                        (CommandSpecificDataRegisterSession)CommandSpecificDataRegisterSession.Deserialize(
                            typeof(CommandSpecificDataRegisterSession), bodyBytes, ref pointer);
                    MsgRegisterSessionReply msg = new MsgRegisterSessionReply();
                    // TODO: check the protocol version to accept the registration
                    msg.CommandSpecificDataRegisterSession = cmdSpecData;
                    m_SessionHandle      = (uint)((DateTime.Now.Ticks / 10) & 0xFFFFFFFF);
                    header.SessionHandle = m_SessionHandle;
                    header.Length        = msg.SizeOf();
                    SendMessage(header, msg);
                    Trace(EventType.Info, string.Format("{0} - Registration session number: {1}", LOG_TAG, header.SessionHandle));
                    break;
                }

                case EncapsulationCommands.SendRRData:
                {
                    if (header.SessionHandle != m_SessionHandle)
                    {
                        throw new Exception(string.Format("Received invalid session handle (unregistred) in SendRRData message: ", header.SessionHandle));
                    }
                    int pointer = 0;
                    MsgUnconnectedSendRequest unconnSndReq = (MsgUnconnectedSendRequest)MsgUnconnectedSendRequest.Deserialize(
                        typeof(MsgUnconnectedSendRequest), bodyBytes, ref pointer);
                    string             symbol   = Encoding.ASCII.GetString(((DataPathSegmentANSISymb)unconnSndReq.CIPConnectionManagerUnconnSnd.CommonIndustrialProtocolRequest.PathSegmentList[0]).ANSISymbol);
                    ElementaryDataType dataType = unconnSndReq.CIPConnectionManagerUnconnSnd.CIPClassGeneric.DataType;
                    OnReceiveData?.Invoke(m_ScktConn.RemoteEndPoint, symbol.Replace("\0", ""), dataType, unconnSndReq.CIPConnectionManagerUnconnSnd.CIPClassGeneric.CIPClassGenericCmdSpecificData);
                    MsgUnconnectedSendReply msg = new MsgUnconnectedSendReply();
                    msg.CommandSpecificDataSendRRData = unconnSndReq.CommandSpecificDataSendRRData;
                    CommandSpecificDataSendRRDataItem item = msg.CommandSpecificDataSendRRData.List.First(
                        a => a.TypeID == CommonPacketItemID.UnconnectedMessage);
                    msg.CommonIndustrialProtocolReply = new CommonIndustrialProtocolReply {
                        Service              = 0xcd,
                        Reserved             = 0x0,
                        GeneralStatus        = 0x0, // <- success
                        AdditionalStatusSize = 0x0,
                        AdditionalStatus     = new ushort[0]
                    };
                    item.Length   = msg.CommonIndustrialProtocolReply.SizeOf();
                    header.Length = msg.SizeOf();
                    SendMessage(header, msg);
                    break;
                }

                case EncapsulationCommands.UnRegisterSession:
                {
                    break;
                }

                default:
                {
                    Trace(EventType.Error, string.Format("{0} - Command {1} not implemented", LOG_TAG, header.Command));
                    break;
                }
                }
            }
            catch (Exception e)
            {
                Trace(e);
            }
        }
Exemplo n.º 11
0
 private Task roomReceiveEvtHandler(int clientID, object obj)
 {
     return(OnReceiveData?.Invoke(clientID, obj));
 }
Exemplo n.º 12
0
 public TilesLayer(ITopPort topPort)
 {
     _topPort = topPort;
     _topPort.OnReceiveParsedData += async data => OnReceiveData?.Invoke(data);
 }
Exemplo n.º 13
0
 public TilesLayer(ITopPort topPort)
 {
     _topPort = topPort;
     _topPort.OnReceiveParsedData += async data => { OnReceiveData?.Invoke(data); await Task.CompletedTask; };
 }
Exemplo n.º 14
0
 /// <summary>
 /// Обработчик при получении данных
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="socketAsyncEventArgs"></param>
 private void RecieveOnCompleted(object sender, SocketAsyncEventArgs socketAsyncEventArgs)
 {
     OnReceiveData?.Invoke(socketAsyncEventArgs.Buffer, socketAsyncEventArgs.Count);
     AwaitRecieveData();
 }