/// <summary>
        /// Reads one frame from the stream
        /// </summary>
        /// <param name="remoteTcpPeer">Remote peer</param>
        /// <param name="leftOvers">Any left overs from previous call or null</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Frame result</returns>
        public virtual async Task <ReadFrameResult> ReadFrameAsync(IRemoteTcpPeer remoteTcpPeer, byte[] leftOvers, CancellationToken cancellationToken)
        {
            bool open;
            int  frameLength;
            var  readBuffer = new byte[this.DefragmentationStrategy.FrameHeaderLength];

            open = await remoteTcpPeer.TcpStream.ReadUntilBufferIsFullAsync(readBuffer, 0, readBuffer.Length, cancellationToken)
                   .ConfigureAwait(false);

            if (!open)
            {
                return(ReadFrameResult.StreamClosedResult);
            }

            frameLength = this.DefragmentationStrategy.GetFrameLength(readBuffer);

            if (frameLength < 1)
            {
                return(ReadFrameResult.FrameDroppedResult);
            }

            var frameBuffer = new byte[frameLength];

            Array.Copy(readBuffer, 0, frameBuffer, 0, readBuffer.Length);

            open = await remoteTcpPeer.TcpStream.ReadUntilBufferIsFullAsync(frameBuffer, readBuffer.Length, frameLength - readBuffer.Length, cancellationToken)
                   .ConfigureAwait(false);

            if (!open)
            {
                return(ReadFrameResult.StreamClosedResult);
            }

            return(new ReadFrameResult(frameBuffer));
        }
Exemple #2
0
 private void ConnectionEstablished(object sender, ConnectionEstablishedEventArgs e)
 {
     log.Info("TpsService: Tps Connection is established.");
     peer = e.RemoteTcpPeer;
     log.Info($"TpsService: Connected to [{peer.IPEndPoint}]");
     TpsConnectionEstablished?.Invoke();
 }
Exemple #3
0
        public async void ConnectToNcc(string ip, int port, string nodeName)
        {
            var client = new AsyncNetTcpClient(ip, port);

            client.ConnectionEstablished += (s, e) =>
            {
                _client = e.RemoteTcpPeer;
                Console.WriteLine($"Connected to CableCloud");

                var hello = $"INIT {nodeName}";
                var bytes = _objectSerializerService.Serialize(hello);
                _client.Post(bytes);
            };
            client.FrameArrived += (s, e) =>
            {
                OnDataReceived(e);
                //Console.WriteLine($"Client received: " +
                //                  $"{System.Text.Encoding.UTF8.GetString(e.FrameData)}");
            };
            await client.StartAsync(CancellationToken.None);

            //_client = new SimpleTcpClient();
            //_client.Connect(ip, port);

            //_logService.LogInfo("Connected to NCC");

            //_client.Write($"INIT {nodeName}");

            //_client.DataReceived += OnDataReceived;
        }
Exemple #4
0
 private void ConnectionClosed(object sender, ConnectionClosedEventArgs e)
 {
     log.Info("TpsService: Connection is Closed.");
     TpsConnectionClosed?.Invoke();
     peer?.Dispose();
     peer = null;
     awaitaiblePeer?.Dispose();
     awaitaiblePeer = null;
 }
Exemple #5
0
 public AwaitaibleRemoteTcpPeer(IRemoteTcpPeer remoteTcpPeer, int frameBufferBoundedCapacity = -1)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
     this.RemoteTcpPeer.FrameArrived     += this.FrameArrivedCallback;
     this.RemoteTcpPeer.ConnectionClosed += this.ConnectionClosedCallback;
     this.frameBuffer = new BufferBlock <byte[]>(new DataflowBlockOptions()
     {
         BoundedCapacity = frameBufferBoundedCapacity
     });
 }
Exemple #6
0
        void InitTcpServer()
        {
            remoteTcpPeerMap = new Dictionary <long, IRemoteTcpPeer>();
            ipEndPointIDMap  = new Dictionary <IPEndPoint, long>();
            Debug.Log("ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId);
            server = new AsyncNetTcpServer(12100);
            server.ConnectionClosed += (sender, e) => //当特定客户端/对等端连接关闭时触发
            {
            };
            server.ConnectionEstablished += (sender, e) => //当新客户机/对等点连接到服务器时触发
            {
                IRemoteTcpPeer peer = e.RemoteTcpPeer;
                Debug.Log($"New connection from [{peer.IPEndPoint}]");
                Debug.Log("ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId);
                long id = IdGenerater.GenerateId();
                remoteTcpPeerMap[id]             = peer;
                ipEndPointIDMap[peer.IPEndPoint] = id;
            };

            server.FrameArrived += (sender, e) =>//TCP帧从特定客户端/对等端到达时触发
            {
                Console.WriteLine($"Server received: {System.Text.Encoding.UTF8.GetString(e.FrameData)}");
                var    peer      = e.RemoteTcpPeer;
                byte[] framedata = e.FrameData;
                int    offser    = 0;
                int    remain    = framedata.Length;
                int    len       = 0;
                int    cmd       = 0;
                while (remain > offser)
                {
                    offser += Utils.Decode32(framedata, offser, ref len);
                    offser += Utils.Decode32(framedata, offser, ref cmd);
                    //offser += Utils.Decode32(framedata, offser, ref cmd);
                    dispatcher[cmd]?.Execute(framedata, offser, len, ipEndPointIDMap[e.RemoteTcpPeer.IPEndPoint]);
                    offser += len;
                }
            };
            server.RemoteTcpPeerExceptionOccured += (sender, e) =>//当处理特定客户机/对等点时发生错误时触发
            {
            };
            server.ServerExceptionOccured += (sender, e) =>//当服务器出现问题时触发
            {
            };
            server.ServerStarted += (sender, e) => //当服务器开始运行时触发
            {
                Console.WriteLine($"Server started on port: " + $"{e.ServerPort}");
            };
            server.UnhandledExceptionOccured += (sender, e) => //当未处理的错误发生时触发——例如,当事件订阅程序抛出异常时
            {
            };

            server.StartAsync(CancellationToken.None);
        }
Exemple #7
0
        public async void StartClientDomain(string ip, int port, string nodeName)
        {
            var clientDomain = new AsyncNetTcpClient(ip, port);

            clientDomain.ConnectionEstablished += (s, e) =>
            {
                _clientDomain = e.RemoteTcpPeer;
                _logService.LogInfo($"Connected to Domain CC and RC");

                var hello = $"INIT {nodeName}";
                var bytes = _objectSerializerService.Serialize(hello);
                _clientDomain.Post(bytes);
            };
            clientDomain.FrameArrived += (s, e) =>
            {
                OnDataReceived(e);
            };
            await clientDomain.StartAsync(CancellationToken.None);
        }
Exemple #8
0
        public async void ConnectToNcc(string ip, int port, string nodeName)
        {
            var client = new AsyncNetTcpClient(ip, port);

            client.ConnectionEstablished += (s, e) =>
            {
                _client = e.RemoteTcpPeer;
                Console.WriteLine($"Connected to NCC");

                var hello = $"INIT {nodeName}";
                var bytes = _objectSerializerService.Serialize(hello);
                _client.Post(bytes);
            };
            client.FrameArrived += (s, e) =>
            {
                OnDataReceived(e);
            };
            await client.StartAsync(CancellationToken.None);
        }
        private void ProcessPackage(IRemoteTcpPeer handler, EonPacket package)
        {
            var incomingNode = _nodeOfSocket[handler];
            var incomingPort = package.Port;

            var cable = GetCable(incomingNode, incomingPort);


            _logService.LogInfo($"Received package from {incomingNode}:{incomingPort}, Content: {package.Content}");

            if (cable == null)
            {
                _logService.LogWarning($"There is no cable, from {incomingNode}:{incomingPort}");
                return;
            }


            var nextNode = cable.Node2;
            var nextPort = cable.Port2;

            if (nextNode == incomingNode)
            {
                nextNode = cable.Node1;
                nextPort = cable.Port1;
            }

            if (cable.Status)
            {
                package.Port = nextPort;
                if (!_socketOfNode.ContainsKey(nextNode))
                {
                    _logService.LogWarning($"{nextNode} is not connected to CableCloud");
                    return;
                }
                SendPacket(_socketOfNode[nextNode], package);
                _logService.LogInfo("Sending package from: " + incomingNode + ":" + incomingPort + " to: " + nextNode + ":" + nextPort);
            }
            else
            {
                _logService.LogInfo("Discarding package (cable disabled) from: " + incomingNode + ":" + incomingPort + " to: " + nextNode + ":" + nextPort);
            }
        }
Exemple #10
0
        private void AddToTranslationDictionary(IRemoteTcpPeer handler, IReadOnlyList <string> parts)
        {
            while (true)
            {
                var success = _nodeOfSocket.TryAdd(handler.TcpClient.Client, parts[1]);
                if (success)
                {
                    break;
                }
                Thread.Sleep(100);
            }

            while (true)
            {
                var success = _socketOfNode.TryAdd(parts[1], handler.TcpClient.Client);
                if (success)
                {
                    break;
                }
                Thread.Sleep(100);
            }
        }
Exemple #11
0
 public ConnectionClosedData(IRemoteTcpPeer remoteTcpPeer, ConnectionCloseReason connectionCloseReason)
 {
     this.RemoteTcpPeer         = remoteTcpPeer;
     this.ConnectionCloseReason = connectionCloseReason;
 }
Exemple #12
0
 public RemoteTcpPeerExceptionEventArgs(IRemoteTcpPeer remoteTcpPeer, Exception ex) : base(ex)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
 }
Exemple #13
0
 public RemoteTcpPeerErrorData(IRemoteTcpPeer remoteTcpPeer, Exception exception) : base(exception)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
 }
 public ConnectionEstablishedData(IRemoteTcpPeer remoteTcpPeer)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
 }
 public void SendMessage(IRemoteTcpPeer handler, ISignalingMessage message)
 {
     handler.Post(_objectSerializerService.Serialize(message));
 }
 public void SendPacket(IRemoteTcpPeer handler, EonPacket package)
 {
     handler.Post(_objectSerializerService.Serialize(package));
 }
        /// <summary>
        /// Reads one frame from the stream
        /// </summary>
        /// <param name="remoteTcpPeer">Remote peer</param>
        /// <param name="leftOvers">Any left overs from previous call or null</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Frame result</returns>
        public virtual async Task <ReadFrameResult> ReadFrameAsync(IRemoteTcpPeer remoteTcpPeer, byte[] leftOvers, CancellationToken cancellationToken)
        {
            byte[] frameBuffer;
            int    readLength;
            int    frameLength = 0;
            int    dataLength  = leftOvers?.Length ?? 0;

            frameBuffer = leftOvers = leftOvers ?? MixedDefragmenter.emptyArray;

            if (dataLength > 0)
            {
                frameLength = this.DefragmentationStrategy.GetFrameLength(frameBuffer, dataLength);
            }

            while (frameLength == 0)
            {
                if (this.DefragmentationStrategy.ReadType == MixedDefragmentationStrategyReadType.ReadFully)
                {
                    if (this.DefragmentationStrategy.ReadBufferLength > dataLength)
                    {
                        frameBuffer = new byte[this.DefragmentationStrategy.ReadBufferLength];
                    }
                    else
                    {
                        frameBuffer = new byte[dataLength];
                    }
                }
                else
                {
                    frameBuffer = new byte[dataLength + this.DefragmentationStrategy.ReadBufferLength];
                }

                if (dataLength > 0)
                {
                    Array.Copy(leftOvers, 0, frameBuffer, 0, dataLength);
                }

                leftOvers = frameBuffer;

                if (this.DefragmentationStrategy.ReadType == MixedDefragmentationStrategyReadType.ReadNewFully)
                {
                    var open = await remoteTcpPeer.TcpStream.ReadUntilBufferIsFullAsync(frameBuffer, dataLength, this.DefragmentationStrategy.ReadBufferLength, cancellationToken)
                               .ConfigureAwait(false);

                    if (!open)
                    {
                        readLength = 0;
                    }
                    else
                    {
                        readLength = this.DefragmentationStrategy.ReadBufferLength;
                    }
                }
                else if (this.DefragmentationStrategy.ReadType == MixedDefragmentationStrategyReadType.ReadFully)
                {
                    var open = await remoteTcpPeer.TcpStream.ReadUntilBufferIsFullAsync(frameBuffer, 0, this.DefragmentationStrategy.ReadBufferLength, cancellationToken)
                               .ConfigureAwait(false);

                    if (!open)
                    {
                        readLength = 0;
                    }
                    else
                    {
                        readLength = this.DefragmentationStrategy.ReadBufferLength;
                    }
                }
                else
                {
                    readLength = await remoteTcpPeer.TcpStream.ReadWithRealCancellationAsync(frameBuffer, dataLength, this.DefragmentationStrategy.ReadBufferLength, cancellationToken)
                                 .ConfigureAwait(false);
                }

                if (readLength < 1)
                {
                    return(ReadFrameResult.StreamClosedResult);
                }

                dataLength += readLength;

                frameLength = this.DefragmentationStrategy.GetFrameLength(frameBuffer, dataLength);

                if (frameLength < 0)
                {
                    return(ReadFrameResult.FrameDroppedResult);
                }
            }

            if (dataLength < frameLength)
            {
                if (frameBuffer.Length < frameLength)
                {
                    frameBuffer = new byte[frameLength];
                    Array.Copy(leftOvers, 0, frameBuffer, 0, dataLength);
                }

                var open = await remoteTcpPeer.TcpStream.ReadUntilBufferIsFullAsync(frameBuffer, dataLength, frameLength - dataLength, cancellationToken)
                           .ConfigureAwait(false);

                if (!open)
                {
                    return(ReadFrameResult.StreamClosedResult);
                }

                dataLength = frameLength;
                leftOvers  = null;
            }
            else if (dataLength > frameLength)
            {
                var frameData       = new byte[frameLength];
                var leftOversLength = dataLength - frameLength;

                leftOvers = new byte[leftOversLength];

                Array.Copy(frameBuffer, 0, frameData, 0, frameLength);
                Array.Copy(frameBuffer, frameLength, leftOvers, 0, leftOversLength);

                frameBuffer = frameData;
            }
            else
            {
                if (frameBuffer.Length > dataLength)
                {
                    frameBuffer = new byte[dataLength];
                    Array.Copy(leftOvers, 0, frameBuffer, 0, dataLength);
                }

                leftOvers = null;
            }

            return(new ReadFrameResult(frameBuffer, leftOvers));
        }
 public ConnectionEstablishedEventArgs(IRemoteTcpPeer remoteTcpPeer)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
 }
Exemple #19
0
 public ConnectionClosedEventArgs(IRemoteTcpPeer remoteTcpPeer)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
 }
 /// <summary>
 /// Creates <see cref="TcpFrameArrivedEventArgs"/> with sender and frame data
 /// </summary>
 /// <param name="remoteTcpPeer">Sender</param>
 /// <param name="frameData">Entire frame data including any headers</param>
 public TcpFrameArrivedEventArgs(IRemoteTcpPeer remoteTcpPeer, byte[] frameData)
 {
     this.RemoteTcpPeer = remoteTcpPeer;
     this.FrameData     = frameData;
 }