コード例 #1
0
ファイル: TCPSmartServer.cs プロジェクト: wjax/CommsPlus
        private async Task DoListenForClients(object state, CancellationToken token)
        {
            TcpListener _server = (state as TcpListener);

            while (!cancelListenToken.IsCancellationRequested)
            {
                logger.Info("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                Socket socket = await _server.AcceptSocketAsync().ConfigureAwait(false);

                // Get ID
                string id = GetIDFromSocket(socket);
                // Create Framewrapper
                var framewrapper = createFrameWrapperFunc();
                // Create Communicator
                CommunicatorBase <U> communicator = new IPSocketCommunicator <U>(socket, framewrapper);

                // Add to dict
                lock (lockerClientList)
                    ClientList.Add(id, communicator);

                // Subscribe to events
                communicator.ConnectionStateEvent += OnCommunicatorConnection;
                communicator.DataReadySyncEvent   += OnCommunicatorSyncData;
                communicator.DataReadyAsyncEvent  += OnCommunicatorAsyncData;
                framewrapper.FrameAvailableEvent  += OnFrameReady;

                communicator.Init(null, false, id, 0);
                communicator.Start();
            }
        }
コード例 #2
0
ファイル: NetRecorder.cs プロジェクト: wjax/CommsPlus
        /// <summary>
        /// Add a multicast peer to the recording
        /// </summary>
        /// <param name="ID">Given ID</param>
        /// <param name="ip">Multicast IP</param>
        /// <param name="port">Multicast destination port</param>
        /// <param name="dumpToFile">True if packets for this peer should be written to individual file</param>
        /// <param name="netcard">Not needed, will join multicast group in all interfaces</param>
        /// <param name="dumpFileExtension">Extension for the individual dump file</param>
        /// <returns>True if peer is added</returns>
        public bool AddPeer(string id, string ip, int port, bool dumpToFile, string netcard = "", string dumpFileExtension = ".dump")
        {
            if (CurrentState == State.Recording)
            {
                logger.Info($"Added Peer {id} - {ip}:{port} Failed. Recording ongoing");
                return(false);
            }

            // Check valid IP
            if (IPAddress.TryParse(ip, out IPAddress ipAddres) && !socketListeners.ContainsKey(id))
            {
                IPSocketCommunicator <object> u = new IPSocketCommunicator <object>();
                u.Init(new ConnUri($"udp://{ip}::{netcard}:{port}"), false, id, 0);
                u.DataReadySyncEvent += DataReadyEventCallback;
                u.DataRateEvent      += OnDataRate;

                RecPeerInfo p = new RecPeerInfo()
                {
                    ID                = id,
                    DumpToFile        = dumpToFile,
                    DumpFileExtension = dumpFileExtension,
                    commsLink         = u,
                    IP                = ip,
                    Port              = port
                };

                socketListeners.Add(id, p);
                _dataRate.Add(id, 0);

                logger.Info($"Added Peer {id} - {ip}:{port} Sucessful");
                return(true);
            }

            return(false);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: wjax/CommsPlus
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello Client!");

            // Crear un Framewrapper. En este casi mi librería ya te da uno hecho para Protobuff que usa Serializer.SerializeWithLengthPrefix(memoryStreamTX, data, PrefixStyle.Base128);
            FrameWrapperBase <MessageBase> frameWrapper1 = new ProtobufFrameWrapper <MessageBase>(true);
            // Crear un TCPCommunicator al que le pasas el framewrapper que ha de usar
            IPSocketCommunicator <MessageBase> client1 = new IPSocketCommunicator <MessageBase>(frameWrapper1);
            // Creas una Uri con el Peer al que quieres conectar
            ConnUri uri1 = new ConnUri("tcp://127.0.0.1:1111");

            // Inicializas el Communicator con la Uri, si quieres q sea persistente (reconecte), el ID, y alguna cosita más
            client1.Init(uri1, true, "CLIENT1", 10000);

            // Te suscribes a los eventos de conexión del communicator y de frame (objeto) disponible del framewrapper
            frameWrapper1.FrameAvailableEvent += OnMessage1;
            client1.ConnectionStateEvent      += OnConnection1;
            client1.DataReadySyncEvent        += OnRawSyncData;
            client1.DataReadyAsyncEvent       += OnRawAsyncData;

            // inicias todo
            client1.Start();

            while (true)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                ChildMessage1 msg = new ChildMessage1()
                {
                    Name = DateTime.Now.ToShortTimeString()
                };

                //TEST
                Dictionary <string, string> payload = new Dictionary <string, string>();
                payload.Add("Jesus", "Roci");
                msg.Payload = new DictionaryPayload {
                    DataDictionary = payload
                };

                _ = client1.SendAsync(msg);

                //while (true)
                //    await Task.Delay(TimeSpan.FromSeconds(1));
            }
        }