/// <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; }
/// <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); } }
/// <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); } }
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); }
/// <summary> /// 显式撤销连接对象 /// </summary> public void Dispose() { if (IsConnected) { Disconnect(); } AllConnections.Remove(this); }
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())) } }); }
/// <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); }
/// <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); } } }
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); } }
/// <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); }
///<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); }
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); } } }
/// <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); }
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); }); }
public void AddConnection(IConnection connection) => AllConnections.Add(connection);
public void Test(string name, int age, string msg) { Current.SendAsync("test", "server", $"欢迎 {name},{age} “{msg}”").Wait(); AllConnections.SendAsync("test", name, msg).Wait(); }
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(); }
/// <summary> /// 显式撤销连接对象 /// </summary> public void Dispose() { Disconnect(); AllConnections.Remove(this); }
private void ClearAllConnections() { AllConnections.Clear(); AllConnectionsList.Clear(); }
public bool RemoveConnection(IConnection connection) => AllConnections.Remove(connection);