예제 #1
0
        /// <summary>
        /// 构造函数
        ///     构造时指定准备使用的通讯协议。
        /// </summary>
        /// <param name="aProtocol">准备使用的通讯协议实例</param>
        public Connection(Protocol aProtocol, string aName)
        {
            Name        = aName;
            _Dispatcher = Dispatcher.CurrentDispatcher;

            // 保存准备使用的通讯协议
            Protocol = aProtocol;
            if (Protocol != null)
            {
                Protocol.ByteFrameReceived   += new System.Action <byte[]>(Protocol_ByteFrameReceived);
                Protocol.StringFrameReceived += new System.Action <string>(Protocol_StringFrameReceived);
                Protocol.ObjectFrameReceived += new System.Action <object>(Protocol_ObjectFrameReceived);
                Protocol.Clarify             += OnProtocol_Clarify;
                ReceiveTimeOut = Protocol.ReceiveTimeOut;
            }

            AllConnections.Add(this);

            _ReceiveBuffer = new byte[ReceiveBufferLength];
            _ReadCallback  = new AsyncCallback(ReadCallback);

            _ReceiveTimeOutTimer          = new DispatcherTimer();
            _ReceiveTimeOutTimer.Interval = ReceiveTimeOut;
            _ReceiveTimeOutTimer.Tick    += OnRecveTimeOut_Tick;

            _HeartbeatTimer          = new DispatcherTimer();
            _HeartbeatTimer.Interval = HeartBeatInterval;
            _HeartbeatTimer.Tick    += OnHeartbeat_Tick;
        }
예제 #2
0
 /// <summary>
 /// Send data through a client using the name of the client
 /// </summary>
 /// <param name="name">Client name</param>
 /// <param name="sendData">Byet buffer with the data to be sent</param>
 /// <param name="nrbytes">Number of bytes to be sent</param>
 /// <returns></returns>
 public bool SendDataAsync(string name, byte[] sendData, int nrbytes)
 {
     if (sendData.Length < nrbytes)
     {
         nrbytes = sendData.Length;
     }
     if (AllConnections.ContainsKey(name))
     {
         TConnection C = AllConnections[name];
         try
         {
             C.ConnectionSocket.BeginSend(C.IncomingData, 0, C.IncomingData.Length, 0, new AsyncCallback(SendCallback), C.Address);
             C.DataReceived = false;
             return(true);
         }
         catch
         {
             ReportError?.Invoke("BeginSend failed in SendDataAsync", "name");
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
예제 #3
0
        /// <summary>
        /// Create a fresh start for an <see cref="Neat"/> object
        /// </summary>
        private void Reset()
        {
            AllConnections.Clear();
            AllNodes.Clear();
            AllClients.Clear();

            for (int i = 0; i < Constants.InputSize; i++)
            {
                NodeGene node = CreateNode();
                node.X = 0.1;;
                node.Y = (i + 1) / (double)(Constants.InputSize + 1);
            }

            for (int i = 0; i < Constants.OutputSize; i++)
            {
                NodeGene node = CreateNode();
                node.X = 0.9;;
                node.Y = (i + 1) / (double)(Constants.OutputSize + 1);

                ActivationEnumeration a = ActivationEnumeration.Random();
                node.Activation     = a.Activation;
                node.ActivationName = a.Name;
            }

            for (int i = 0; i < Constants.MaxClients; i++)
            {
                Client c = new Client(EmptyGenome());
                AllClients.Add(c);
            }
        }
예제 #4
0
 protected override async Task ClientStartListen(HttpConnection connection)
 {
     if (connection.NetworkStream == null && DualSettings.Certificate != null &&
         connection.NetworkClient != null
         )
     {
         var peaker = new StreamPeaker(connection.NetworkClient.GetStream());
         var mark   = peaker.FirstByte;
         if (mark != 0 && (mark < 32 || mark >= 127))
         {
             var ssl = new SslStream(peaker, false);
             connection.NetworkStream = ssl;
             ssl.AuthenticateAsServer(
                 serverCertificate:          DualSettings.Certificate,
                 clientCertificateRequired:  false,
                 enabledSslProtocols:        SslProtocols.None,
                 checkCertificateRevocation: true
                 );
             if (!ssl.IsAuthenticated)
             {
                 ssl.Dispose();
                 connection.NetworkClient.Close();
                 AllConnections.Remove(connection);
                 return;
             }
         }
         else
         {
             connection.NetworkStream = peaker;
         }
     }
     await base.ClientStartListen(connection).ConfigureAwait(false);
 }
예제 #5
0
 /// <summary>
 /// 显式撤销连接对象
 /// </summary>
 public void Dispose()
 {
     if (IsConnected)
     {
         Disconnect();
     }
     AllConnections.Remove(this);
 }
예제 #6
0
 public JObject Serialize()
 {
     return(new JObject
     {
         { "Name", Name },
         { "Desc", Description },
         { "Nodes", new JArray(AllNodes.Select(x => x.Serialize())) },
         { "Connections", new JArray(AllConnections.Select(x => x.Serialize())) }
     });
 }
예제 #7
0
파일: Connections.cs 프로젝트: Omybot/GoBot
        /// <summary>
        /// Ajoute une connexion UDP aux connexions suivies
        /// </summary>
        /// <param name="board">Carte associée à la connexion</param>
        /// <param name="ip">Adresse IP de la connexion</param>
        /// <param name="inPort">Port d'entrée pour le PC</param>
        /// <param name="outPort">Port de sortie pour le PC</param>
        /// <returns>La connexion créée</returns>
        private static UDPConnection AddUDPConnection(Board board, IPAddress ip, int inPort, int outPort)
        {
            UDPConnection output = new UDPConnection();

            output.Connect(ip, inPort, outPort);
            UDPBoardConnection.Add(board, output);
            EnableConnection.Add(board, true);
            AllConnections.Add(output);
            output.ConnectionChecker.SendConnectionTest += ConnexionCheck_SendConnectionTestUDP;

            return(output);
        }
예제 #8
0
파일: Connections.cs 프로젝트: Omybot/GoBot
        /// <summary>
        /// Boucle de tests de connexions pour maintenir les vérification à intervalle régulier
        /// </summary>
        private static void TestConnections()
        {
            int interval = IntervalLoopTests / AllConnections.Count();

            foreach (Connection conn in AllConnections.OrderBy(c => Connections.GetUDPBoardByConnection(c).ToString()))
            {
                if (!_linkTestConnections.Cancelled)
                {
                    conn.ConnectionChecker.CheckConnection();
                    Thread.Sleep(interval);
                }
            }
        }
예제 #9
0
        private void AcceptConnectCallback(IAsyncResult ar)
        {
            Listener = (Socket)ar.AsyncState;

            //acknowledge the connection
            Socket incomingSocket = null;

            try
            {
                incomingSocket = Listener.EndAccept(ar);
            }
            catch
            {
                ReportError?.Invoke("EndAccept failed on incoming connection", "");
            }

            //put the listener back to listening
            Listener.BeginAccept(new AsyncCallback(AcceptConnectCallback), Listener);

            if (incomingSocket == null)
            {
                return;
            }
            IPEndPoint ep = (IPEndPoint)incomingSocket.RemoteEndPoint;

            TConnection C = new TConnection();

            C.Setup(incomingSocket, ep.Address, ep.Port, ConnectionBufSize);

            if (AllConnections.ContainsKey(C.Address) == false)
            {
                AllConnections.Add(C.Address, C);
                AllConnectionsList.Add(C);
            }

            //Signal that a new connection has been created
            NewConnection?.Invoke(C);

            //configure the socket to receive incoming data and arm the data reception event
            try
            {
                C.ConnectionSocket.BeginReceive(C.IncomingData, 0, C.IncomingData.Length, 0, new AsyncCallback(ReadCallback), C.Address);
            }
            catch
            {
                ReportError?.Invoke("BeginReceive failed on new connection", C.Address);
            }
        }
예제 #10
0
        /// <summary>
        /// Disconnect a client and remove it form the client list
        /// </summary>
        /// <param name="name">Client name</param>
        public void RemoveConnection(string name)
        {
            if (!AllConnections.ContainsKey(name))
            {
                return;
            }

            TConnection Conn = AllConnections[name];

            AllConnectionsList.Remove(Conn);

            Conn.IncomingData = null;
            Conn.OutgoingData = null;

            AllConnections.Remove(name);
        }
예제 #11
0
        ///<inheritdoc/>
        public ConnectionGene GetConnection(NodeGene In, NodeGene Out)
        {
            ConnectionGene connection = new ConnectionGene(In, Out);

            if (AllConnections.ContainsKey(connection))
            {
                connection.InnovationNumber = AllConnections[connection].InnovationNumber;
            }
            else
            {
                connection.InnovationNumber = AllConnections.Count + 1;
                AllConnections.Add(connection, connection);
            }

            return(connection);
        }
예제 #12
0
        private void CleanupConnections(object sender)
        {
            for (int i = 0; i < AllConnectionsList.Count; i++)
            {
                var C = AllConnectionsList[i];
                if (C.ConnStats.HasTimedOut)
                {
                    if (C.ConnectionSocket.Connected)
                    {
                        C.ConnectionSocket.Disconnect(false);
                    }

                    AllConnectionsList.Remove(C);
                    AllConnections.Remove(C.Address);
                }
            }
        }
예제 #13
0
        /// <summary>
        /// 构造函数
        ///     构造时指定准备使用的通讯协议。
        /// </summary>
        /// <param name="aProtocol">准备使用的通讯协议实例</param>
        public Connection(Protocol aProtocol)
        {
            // 指定默认属性值
            IdleInterval        = 10;
            ReceiveTimeOut      = TimeSpan.Zero;
            ExitTimeoutInterval = 2000;
            HeartBeatInterval   = TimeSpan.FromSeconds(2);

            // 保存准备使用的通讯协议
            _Protocol = aProtocol;
            if (_Protocol != null)
            {
                _Protocol.ByteFrameReceived   += new System.Action <byte[]>(Protocol_ByteFrameReceived);
                _Protocol.StringFrameReceived += new System.Action <string>(Protocol_StringFrameReceived);
                _Protocol.ObjectFrameReceived += new System.Action <object>(Protocol_ObjectFrameReceived);
                _Protocol.Clarify             += OnProtocol_Clarify;
                ReceiveTimeOut = _Protocol.ReceiveTimeOut;
            }

            AllConnections.Add(this);
        }
예제 #14
0
        protected virtual void SecureClientConnected(TcpClient client)
        {
            if (SecureSettings.Certificate == null)
            {
                client.Close();
                return;
            }
            //prepare session
            var connection = new HttpConnection()
            {
                NetworkClient = client,
                Ip            = client.Client.RemoteEndPoint is IPEndPoint iPEndPoint
                    ? iPEndPoint.Address.ToString()
                    : client.Client.RemoteEndPoint?.ToString(),
            };

            AllConnections.Add(connection);
            //listen to connection
            _ = Task.Run(async() =>
            {
                //authentificate as server and establish ssl connection
                var stream = new SslStream(client.GetStream(), false);
                connection.NetworkStream = stream;
                stream.AuthenticateAsServer(
                    serverCertificate:          SecureSettings.Certificate,
                    clientCertificateRequired:  false,
                    enabledSslProtocols:        SslProtocols.None,
                    checkCertificateRevocation: true
                    );
                if (!stream.IsAuthenticated)
                {
                    stream.Dispose();
                    client.Close();
                    AllConnections.Remove(connection);
                    return;
                }

                await SafeClientStartListen(connection).ConfigureAwait(false);
            });
        }
예제 #15
0
 public void AddConnection(IConnection connection) => AllConnections.Add(connection);
예제 #16
0
 public void Test(string name, int age, string msg)
 {
     Current.SendAsync("test", "server", $"欢迎 {name},{age} “{msg}”").Wait();
     AllConnections.SendAsync("test", name, msg).Wait();
 }
예제 #17
0
 public void TestJson(Person p, string msg)
 {
     Current.SendAsync("testJson", new { Name = "server" }, $"欢迎 {p.Name},{p.Age} “{msg}”").Wait();
     AllConnections.SendAsync("testJson", new { p.Name }, msg).Wait();
 }
예제 #18
0
 /// <summary>
 /// 显式撤销连接对象
 /// </summary>
 public void Dispose()
 {
     Disconnect();
     AllConnections.Remove(this);
 }
예제 #19
0
 private void ClearAllConnections()
 {
     AllConnections.Clear();
     AllConnectionsList.Clear();
 }
예제 #20
0
 public bool RemoveConnection(IConnection connection) => AllConnections.Remove(connection);