示例#1
0
        private void readCallback(IAsyncResult ar)
        {
            try
            {
                netStream.EndRead(ar);
                NetworkMessage netMesasge = new NetworkMessageFormatter <NetworkMessage>().Deserialize(ar.AsyncState as byte[]);
                if (netMesasge != null)
                {
                    ReadCompleted?.Invoke(this, new NetworkMessageReaderReadCompletedEventArgs(netMesasge, TcpClient));
                }
                else
                {
                    ReadError?.Invoke(this, new NetworkMessageReaderReadErrorEventArgs(TcpClient, new ArgumentNullException("NetworkMessage is null")));
                }


                if (readLoop)
                {
                    ReadAsync(readLoop);
                }
            }
            catch (Exception ex)
            {
                ReadError?.Invoke(this, new NetworkMessageReaderReadErrorEventArgs(TcpClient, ex));
            }
        }
        private void ReadThread()
        {
            byte[] dataLength = new byte[4];

            while (running)
            {
                try
                {
                    stream.Read(dataLength, 0, 4);

                    int    readedData = 0, totalData = BitConverter.ToInt32(dataLength, 0);
                    byte[] data = new byte[totalData];

                    do
                    {
                        readedData += stream.Read(data, readedData, totalData - readedData);
                    } while (readedData < totalData);

                    if (data.Length > 0)
                    {
                        Received?.Invoke(serializer.Deserialize(data));
                    }
                }
                catch (Exception ex)
                {
                    ReadError?.Invoke(ex);
                }

                Thread.Sleep(THREAD_WAITING_TIME);
            }
        }
示例#3
0
        public void Complete(int bytes_transferred, bool success, int error, object context)
        {
            ReadError exception = null;

            try
            {
                if (!success)
                {
                    exception = new ReadError(error);
                }
                else if (0 == bytes_transferred)
                {
                    exception = new ReadError(new SocketException((int)SocketError.Shutdown), "¶Á0¸ö×Ö½Ú!");
                }
                else
                {
                    _byteBuffer.End += bytes_transferred;
                    _transport.OnRead(_byteBuffer);
                    return;
                }
            }
            catch (ReadError err)
            {
                exception = err;
            }
            catch (Exception e)
            {
                exception = new ReadError(e, e.Message);
            }

            _transport.OnException(exception);
        }
        public void Open(ILogRecordFormat recordFormat)
        {
            var fileName = Properties.Settings.Default.TextFilePath;

            _logger.Info("Открытие файла {0}", fileName);
            _recordFormat   = recordFormat;
            _cts            = new CancellationTokenSource();
            _file           = new StreamReader(fileName);
            _messageCounter = 0;

            var readTask = Task.Run(async() =>
            {
                _logger.Info("Запуск потока чтения файла");

                string line;
                while ((line = _file.ReadLine()) != null)
                {
                    _messageCounter++;
                    DataReceived?.Invoke(this, new ReceiveEventArgs()
                    {
                        Data = Encoding.ASCII.GetBytes(line)
                    });
                    await Task.Delay(10, _cts.Token);
                }
            }, _cts.Token);

            readTask.ContinueWith(_ => ReadError?.Invoke(this, new ErrorEventArgs(_.Exception)), TaskContinuationOptions.OnlyOnFaulted);
        }
示例#5
0
        public void Open(ILogRecordFormat recordFormat)
        {
            _recordFormat   = recordFormat;
            _messageCounter = 0;

            InitReceiver();

            Task.Run(() => Read(), _cts.Token).ContinueWith(_ => ReadError?.Invoke(this, new ErrorEventArgs(_.Exception)), TaskContinuationOptions.OnlyOnFaulted);
        }
        private void Connect(TcpClient client)
        {
            connection = ConnectionFactory.GetConnection(client);

            connection.Open();
            connection.Received   += message => ResponseReceived(message);
            connection.ReadError  += exception => ReadError?.Invoke(exception);
            connection.WriteError += exception => WriteError?.Invoke(exception);
        }
示例#7
0
 public static IConnectionConfiguration CopyWith(
     this IConnectionConfiguration configuration,
     IRetry connectionRetry                    = null,
     IVersionSupport versionSupport            = null,
     TimeSpan?requestTimeout                   = null,
     int?readBufferSize                        = null,
     int?writeBufferSize                       = null,
     bool?isTcpKeepalive                       = null,
     IEnumerable <IMembershipEncoder> encoders = null,
     ISslConfiguration sslConfiguration        = null,
     ConnectError onDisconnected               = null,
     Connecting onConnecting                   = null,
     Connecting onConnected                    = null,
     Writing onWriting            = null,
     StartingBytes onWritingBytes = null,
     FinishedBytes onWroteBytes   = null,
     WriteSuccess onWritten       = null,
     WriteError onWriteFailed     = null,
     Reading onReading            = null,
     StartingBytes onReadingBytes = null,
     FinishedBytes onReadBytes    = null,
     ReadSuccess onRead           = null,
     ReadError onReadFailed       = null,
     ProduceRequestMessages onProduceRequestMessages = null)
 {
     return(new ConnectionConfiguration(
                connectionRetry ?? configuration.ConnectionRetry,
                versionSupport ?? configuration.VersionSupport,
                requestTimeout ?? configuration.RequestTimeout,
                readBufferSize ?? configuration.ReadBufferSize,
                writeBufferSize ?? configuration.WriteBufferSize,
                isTcpKeepalive ?? configuration.IsTcpKeepalive,
                encoders ?? configuration.Encoders.Values,
                sslConfiguration ?? configuration.SslConfiguration,
                onDisconnected ?? configuration.OnDisconnected,
                onConnecting ?? configuration.OnConnecting,
                onConnected ?? configuration.OnConnected,
                onWriting ?? configuration.OnWriting,
                onWritingBytes ?? configuration.OnWritingBytes,
                onWroteBytes ?? configuration.OnWroteBytes,
                onWritten ?? configuration.OnWritten,
                onWriteFailed ?? configuration.OnWriteFailed,
                onReading ?? configuration.OnReading,
                onReadingBytes ?? configuration.OnReadingBytes,
                onReadBytes ?? configuration.OnReadBytes,
                onRead ?? configuration.OnRead,
                onReadFailed ?? configuration.OnReadFailed,
                onProduceRequestMessages ?? configuration.OnProduceRequestMessages));
 }
示例#8
0
        public void ReadAsync(bool readLoop = false)
        {
            try
            {
                this.readLoop = readLoop;

                byte[] buffer = new byte[TcpClient.ReceiveBufferSize = NetworkMessage.MAX_DATA_SIZE_IN_BYTES];
                netStream = TcpClient.GetStream();
                netStream.BeginRead(buffer, 0, buffer.Length, readCallback, buffer);
            }
            catch (Exception ex)
            {
                ReadError?.Invoke(this, new NetworkMessageReaderReadErrorEventArgs(TcpClient, ex));
            }
        }
示例#9
0
 /// <summary>
 /// Configuration for the tcp connection.
 /// </summary>
 /// <param name="connectionRetry">Retry details for (re)establishing the connection.</param>
 /// <param name="versionSupport">Support for different protocol versions for Kakfa requests and responses.</param>
 /// <param name="requestTimeout">The maximum time to wait for requests.</param>
 /// <param name="readBufferSize">The buffer size to use for the socket, when receiving bytes.</param>
 /// <param name="writeBufferSize">The buffer size to use for the socket, when sending bytes.</param>
 /// <param name="isTcpKeepalive">TCP keepalive option.</param>
 /// <param name="encoders">Custom Encoding support for different protocol types</param>
 /// <param name="sslConfiguration">Configuration for SSL encrypted communication</param>
 /// <param name="onDisconnected">Triggered when the tcp socket is disconnected.</param>
 /// <param name="onConnecting">Triggered when the tcp socket is connecting.</param>
 /// <param name="onConnected">Triggered after the tcp socket is successfully connected.</param>
 /// <param name="onWriting">Triggered when writing to the tcp stream.</param>
 /// <param name="onWritingBytes">Triggered when writing a chunk of bytes to the tcp stream.</param>
 /// <param name="onWroteBytes">Triggered after successfully writing a chunk of bytes to the tcp stream.</param>
 /// <param name="onWritten">Triggered after having successfully written to the tcp stream.</param>
 /// <param name="onWriteFailed">Triggered after failing to write to the tcp stream.</param>
 /// <param name="onReading">Triggered when starting to read a message's bytes from the tcp stream.</param>
 /// <param name="onReadingBytes">Triggered when reading a chunk of bytes from the tcp stream.</param>
 /// <param name="onReadBytes">Triggered after successfully reading a chunk of bytes from the tcp stream.</param>
 /// <param name="onRead">Triggered after having successfully read a message's bytes from the tcp stream.</param>
 /// <param name="onReadFailed">Triggered after failing to read from the tcp stream.</param>
 /// <param name="onProduceRequestMessages">Triggered when encoding ProduceRequest messages.</param>
 public ConnectionConfiguration(
     IRetry connectionRetry                    = null,
     IVersionSupport versionSupport            = null,
     TimeSpan?requestTimeout                   = null,
     int?readBufferSize                        = null,
     int?writeBufferSize                       = null,
     bool?isTcpKeepalive                       = null,
     IEnumerable <IMembershipEncoder> encoders = null,
     ISslConfiguration sslConfiguration        = null,
     ConnectError onDisconnected               = null,
     Connecting onConnecting                   = null,
     Connecting onConnected                    = null,
     Writing onWriting            = null,
     StartingBytes onWritingBytes = null,
     FinishedBytes onWroteBytes   = null,
     WriteSuccess onWritten       = null,
     WriteError onWriteFailed     = null,
     Reading onReading            = null,
     StartingBytes onReadingBytes = null,
     FinishedBytes onReadBytes    = null,
     ReadSuccess onRead           = null,
     ReadError onReadFailed       = null,
     ProduceRequestMessages onProduceRequestMessages = null
     )
 {
     ConnectionRetry          = connectionRetry ?? Defaults.ConnectionRetry();
     VersionSupport           = versionSupport ?? Connections.VersionSupport.Kafka10;
     RequestTimeout           = requestTimeout ?? TimeSpan.FromSeconds(Defaults.RequestTimeoutSeconds);
     ReadBufferSize           = readBufferSize.GetValueOrDefault(Defaults.BufferSize);
     WriteBufferSize          = writeBufferSize.GetValueOrDefault(Defaults.BufferSize);
     IsTcpKeepalive           = isTcpKeepalive ?? Defaults.IsTcpKeepalive;
     Encoders                 = Defaults.Encoders(encoders);
     SslConfiguration         = sslConfiguration;
     OnDisconnected           = onDisconnected;
     OnConnecting             = onConnecting;
     OnConnected              = onConnected;
     OnWriting                = onWriting;
     OnWritingBytes           = onWritingBytes;
     OnWroteBytes             = onWroteBytes;
     OnWritten                = onWritten;
     OnWriteFailed            = onWriteFailed;
     OnReading                = onReading;
     OnReadingBytes           = onReadingBytes;
     OnReadBytes              = onReadBytes;
     OnRead                   = onRead;
     OnReadFailed             = onReadFailed;
     OnProduceRequestMessages = onProduceRequestMessages;
 }
示例#10
0
        private void ListenThread()
        {
            listener.Start();

            while (running)
            {
                TcpClient        client           = listener.AcceptTcpClient();
                ClientConnection clientConnection = new ClientConnection(ConnectionFactory.GetConnection(client), new Client(false));

                clientConnection.Connection.Received   += message => MessageReceived(message, clientConnection);
                clientConnection.Connection.ReadError  += exception => ReadError?.Invoke(exception, clientConnection.Connection, clientConnection.Client);
                clientConnection.Connection.WriteError += exception => WriteError?.Invoke(exception, clientConnection.Connection, clientConnection.Client);
                clientConnection.Connection.Open();

                connections.Add(clientConnection);
            }
        }
示例#11
0
        /// <summary>
        /// Configuration for the tcp connection.
        /// </summary>
        /// <param name="connectionRetry">Retry details for (re)establishing the connection.</param>
        /// <param name="versionSupport">Support for different protocol versions for Kakfa requests and responses.</param>
        /// <param name="requestTimeout">The maximum time to wait for requests.</param>
        /// <param name="encoders">Custom Encoding support for different protocol types</param>
        /// <param name="sslConfiguration">Configuration for SSL encrypted communication</param>
        /// <param name="onDisconnected">Triggered when the tcp socket is disconnected.</param>
        /// <param name="onConnecting">Triggered when the tcp socket is connecting.</param>
        /// <param name="onConnected">Triggered after the tcp socket is successfully connected.</param>
        /// <param name="onWriteEnqueued">Triggered after enqueing async write task for writing to the tcp stream.</param>
        /// <param name="onWriting">Triggered when writing to the tcp stream.</param>
        /// <param name="onWritten">Triggered after having successfully written to the tcp stream.</param>
        /// <param name="onWriteFailed">Triggered after failing to write to the tcp stream.</param>
        /// <param name="onReading">Triggered when starting to read a message's bytes from the tcp stream.</param>
        /// <param name="onReadingChunk">Triggered when reading a chunk of bytes from the tcp stream.</param>
        /// <param name="onReadChunk">Triggered after successfully reading a chunk of bytes from the tcp stream.</param>
        /// <param name="onRead">Triggered after having successfully read a message's bytes from the tcp stream.</param>
        /// <param name="onReadFailed">Triggered after failing to read from the tcp stream.</param>
        /// <param name="onProduceRequestMessages">Triggered when encoding ProduceRequest messages.</param>
        public ConnectionConfiguration(
            IRetry connectionRetry         = null,
            IVersionSupport versionSupport = null,
            TimeSpan?requestTimeout        = null,
            IEnumerable <IProtocolTypeEncoder> encoders = null,
            ISslConfiguration sslConfiguration          = null,
            ConnectError onDisconnected = null,
            Connecting onConnecting     = null,
            Connecting onConnected      = null,
            Writing onWriteEnqueued     = null,
            Writing onWriting           = null,
            WriteSuccess onWritten      = null,
            WriteError onWriteFailed    = null,
            Reading onReading           = null,
            ReadingChunk onReadingChunk = null,
            ReadChunk onReadChunk       = null,
            Read onRead            = null,
            ReadError onReadFailed = null,
            ProduceRequestMessages onProduceRequestMessages = null
            )
        {
            ConnectionRetry = connectionRetry ?? Defaults.ConnectionRetry();
            VersionSupport  = versionSupport ?? Connections.VersionSupport.Kafka8;
            RequestTimeout  = requestTimeout ?? TimeSpan.FromSeconds(Defaults.RequestTimeoutSeconds);
            Encoders        = encoders != null
                ? encoders.ToImmutableDictionary(e => e.Type)
                : ImmutableDictionary <string, IProtocolTypeEncoder> .Empty;

            SslConfiguration         = sslConfiguration;
            OnDisconnected           = onDisconnected;
            OnConnecting             = onConnecting;
            OnConnected              = onConnected;
            OnWriteEnqueued          = onWriteEnqueued;
            OnWriting                = onWriting;
            OnWritten                = onWritten;
            OnWriteFailed            = onWriteFailed;
            OnReading                = onReading;
            OnReadingChunk           = onReadingChunk;
            OnReadChunk              = onReadChunk;
            OnRead                   = onRead;
            OnReadFailed             = onReadFailed;
            OnProduceRequestMessages = onProduceRequestMessages;
        }
示例#12
0
    //each port is constantly running this function, basically just lisening for chars
    //to come through and will build a command, once it finds a null character then the
    //command must be complete
    public IEnumerator readPort(SerialPort sp)
    {
        //List<char> currentCommand = new List<char>();

        Debug.Log("starting reading on port: " + sp.PortName);
        RecieveCommand currentCommand = null;

        //constantly checking if there is an incoming char to the specific serial port
        //if there is a char to read, then it adds it to the current command
        //if there is not a char to read it just continues.

        while (true)
        {
            //check if device was disconnected
            bool debugInitializedAndPopulated = debugCommandsDictionary.ContainsKey(sp) && debugCommandsDictionary[sp].Count != 0;

            //if it has bytes to read OR the debug array exists AND had stuff in it

            //if (debugInitializedAndPopulated) {
            //    Debug.Log(debugCommandsDictionary[sp].Dequeue());
            //}



            while ((debugInitializedAndPopulated || (sp.IsOpen && sp.BytesToRead > 0)))
            {
                try
                {
                    //I should be parsing it as they come in
                    byte incomingByte;


                    if (debugInitializedAndPopulated)
                    {
                        incomingByte = debugCommandsDictionary[sp].Dequeue();
                        debugInitializedAndPopulated = debugCommandsDictionary.ContainsKey(sp) && debugCommandsDictionary[sp].Count != 0;
                    }
                    else
                    {
                        //incomingByte = (byte)sp.ReadChar();

                        if (sp.IsOpen)
                        {
                            incomingByte = (byte)sp.ReadChar();
                        }
                        else
                        {
                            throw new TimeoutException();
                        }
                    }
                    //reject all commands if the game is paused except for vote:)
                    if (currentCommand == null)
                    {
                        //spawns a new command
                        switch ((char)incomingByte)
                        {
                        case 'r':
                            if (gamePaused)
                            {
                                break;
                            }
                            Debug.Log("setting new command to I AM for sp " + sp.PortName);
                            currentCommand = new RecieveIAm(sp);
                            break;

                        case 'n':
                            if (gamePaused || !gameStarted)
                            {
                                break;
                            }
                            Debug.Log("setting new command to CREATE TRAIN");
                            currentCommand = new CreateTrain();
                            break;

                        case 'o':
                            if (gamePaused || !gameStarted)
                            {
                                break;
                            }
                            Debug.Log("setting new command to STOP TRAIN PRESSED");
                            currentCommand = new StopTrainPressed();
                            break;

                        case 'p':
                            if (gamePaused || !gameStarted)
                            {
                                break;
                            }
                            Debug.Log("setting new command to ANSWER TRAIN");
                            currentCommand = new AnswerTrain();
                            break;

                        case 'q':
                            Debug.Log("setting new command to SEND VOTE");
                            currentCommand = new SendVote();
                            break;

                        case 'i':
                            Debug.Log("setting new command to RECIEVE SET SPEED");
                            currentCommand = new RecieveSetSpeed();
                            break;

                        case 'u':
                            Debug.Log("setting new command to START RESYNC");
                            currentCommand = new RecieveStartResync();
                            break;

                        case 'v':
                            Debug.Log("setting new command to END RESYNC");
                            currentCommand = new RecieveEndResync();
                            break;

                        case 's':
                            //Debug.Log("setting new command to DEBUG");
                            currentCommand = new ReadError();
                            ((ReadError)currentCommand).whoAmI = sp.PortName;
                            break;

                        case 'z':
                            //Debug.Log("setting new command to DEBUG");
                            Debug.Log("setting new command to RECIEVE PONG");
                            currentCommand = new RecievePongFromLEDArduino();
                            break;

                        case 'A':
                            Debug.Log("setting new command to RECIEVE TRAIN PING");
                            //Debug.Log("setting new command to DEBUG");
                            currentCommand = new RecieveTrainPing();
                            break;

                        default:
                            Debug.LogError("Unable to figure out command sent to me: " + incomingByte + " " + (char)incomingByte);
                            break;
                        }
                    }
                    else
                    {
                        if (incomingByte == 0)
                        {
                            if (currentCommand != null)
                            {
                                currentCommand.executePopulatedMessage();
                                currentCommand = null;
                            }
                        }
                        else
                        {
                            currentCommand.readNextByte(incomingByte);
                        }
                    }
                }
                catch (TimeoutException)
                {
                    //Debug.Log("timeout exception");
                }
            }
            yield return(null);
        }
    }
示例#13
0
 internal GenericReadOperation(ReadHandle handle, NativeArray <byte> buffer)
 {
     m_Err    = ReadError.InProgress;
     m_Handle = handle;
     m_Buffer = buffer;
 }