virtual internal void OnNewConnection(INetworkNode Remote) { if (Remote == null) { return; } if (!Remotes.Contains(Remote)) { Remotes.Add(Remote); } if (NewConnection == null) { return; } Task.Run(() => { NewConnection?.Invoke(this, new InternetConnectionEventArgs { Local = this, Remote = Remote }); }); }
/// <summary> /// Method executed by the client listening thread /// </summary> /// <param name="threadArgs">An object encapsulating the server node connection</param> private void MessageListenerAction(object threadArgs) { INetworkNode senderNode = (INetworkNode)threadArgs; Socket socket = senderNode.Socket; socket.ReceiveBufferSize = ReceiveBufferSize; if (ReceiveTimeOut > 0) { socket.ReceiveTimeout = ReceiveTimeOut; } while (true) { byte[] buffer = new byte[socket.ReceiveBufferSize]; int received = socket.Receive(buffer); if (received > 0) { if (OnReceivedStreamMessage != null) { SocketEventArgs args = new SocketEventArgs(buffer.Take(received).ToArray(), senderNode); OnReceivedStreamMessage(socket, args); } } else { //timed out socket.Disconnect(false); break; } } }
public void unRegister(INetworkNode node) { if (listeners.Contains(node)) { listeners.Remove(node); } }
public void ListenForMessages(INetworkNode Remote) { byte[] RecvBuffer = new byte[ReceiveBufferSize]; int bytesRead = 1; while (bytesRead > 0) { try { bytesRead = Remote.Socket.Receive(RecvBuffer, SocketFlags.None); if (bytesRead <= 0) { CloseRemote(Remote); } else { this.OnBytesReceived(Remote, bytesRead); byte[] Data = new byte[bytesRead]; Buffer.BlockCopy(RecvBuffer, 0, Data, 0, bytesRead); this.OnIncomingMessage(Remote, Data); } } catch (SocketException) { // If we catch a socket exception, it's probably a fatal error or the socket is disconnected; abort the connection bytesRead = 0; CloseRemote(Remote); } } }
/// <summary> /// Used by clients to send data over an established connection in a connection-oriented protocol /// </summary> /// <param name="message">Message data</param> /// <param name="receiver">Connected receiver of message</param> /// <returns>A status indicating result of the operation</returns> public IStatus <string> Stream(byte[] message, INetworkNode receiver) { Socket recipient = null; if (ConnectedServer != null && ConnectedServer.GetHashCode() == receiver.GetHashCode())//check if its server { recipient = ConnectedServer.Socket; } else { foreach (var client in ConnectedClients.Keys) { if (client.GetHashCode() == receiver.GetHashCode()) { recipient = client.Socket; } } } IStatus <string> status = Util.Container.CreateInstance <IStatus <string> >(); if (recipient == null) { status.IsSuccess = false; status.StatusMessage = "No matching server or client node found in the list of connected nodes"; } else { recipient.Send(message); status.IsSuccess = true; status.StatusMessage = "Message Sent"; } return(status); }
public void SendLine(INetworkNode Remote, byte[] DataLine) { byte[] Line = new byte[DataLine.Length + PacketType.EndOfLine.Length]; System.Buffer.BlockCopy(DataLine, 0, Line, 0, DataLine.Length); System.Buffer.BlockCopy(PacketType.EndOfLine, 0, Line, DataLine.Length, PacketType.EndOfLine.Length); this.Send(Remote, Line); }
public override void Shutdown() { INetworkNode node = m_Adapter.NetworkNode; m_Adapter.Unload(); node.UnloadNode(); base.Shutdown(); }
private async void btnDisconnectClient_Click(object sender, EventArgs e) { INetworkNode SelectedClient = GetSelectedClient(); if ((Server != null) && (SelectedClient != null)) { await Server.DisconnectAsync(SelectedClient); } }
/// <summary> /// Used by nodes to send data over a one-time link in a connectionless protocol /// </summary> /// <param name="message">Message data</param> /// <param name="receiver">Recipient node</param> /// <returns>A status indicating result of the operation</returns> public IStatus <string> SendDatagram(byte[] message, INetworkNode receiver) { receiver.Socket.SendTo(message, receiver.Socket.RemoteEndPoint); IStatus <string> status = Util.Container.CreateInstance <IStatus <string> >(); status.IsSuccess = true; status.StatusMessage = "Message Sent"; return(status); }
public void register(INetworkNode node) { if (!listeners.Contains(node)) { listeners.Add(node); } node.RegisterInput(this); }
private async void btnSendToSelected_Click(object sender, EventArgs e) { INetworkNode SelectedClient = GetSelectedClient(); if ((Server != null) && (SelectedClient != null)) { await Server.SendLineAsync(SelectedClient, UTF8Encoding.UTF8.GetBytes(txtToSend.Text)); } }
public virtual void Send(INetworkNode Remote, byte[] Message) { this.OnOutgoingMessage(Remote, Message); int bytesSent = Remote.Socket.Send(Message); if (bytesSent > 0) { this.OnBytesSent(Remote, bytesSent); } }
internal virtual void OnMessageReceived(INetworkNode From, byte[] NewMessage) { MessageReceived?.Invoke(this, new InternetCommunicationEventArgs() { Remote = From, Local = Parent, Direction = CommunicationDirection.Inbound, Message = NewMessage }); }
/// <summary> /// Initializes a new instance of the <see cref="NetworkArc"/> class. Initializes a new arc defining information between 2 points. /// </summary> /// <param name="source"> /// The source node of the arc. /// </param> /// <param name="destination"> /// The destination node of the arc. /// </param> /// <param name="time"> /// The total time of the arc. /// </param> /// <param name="distance"> /// The total distance in Km of the arc. /// </param> /// <param name="departureTime"> /// The departure time of this arc. Set to default(DateTime) if departure time is not relevant. /// </param> /// <param name="transportMode"> /// Sets the transport id used in the arc. /// </param> public NetworkArc( INetworkNode source, INetworkNode destination, TransportTimeSpan time, double distance, DateTime departureTime, string transportMode) : base((Location)source, (Location)destination, time, distance, departureTime, transportMode) { }
/// <summary> /// Opens a port for receiving incoming connections from a client white-list /// </summary> /// <param name="validClients">Client white list</param> public void Listen(ISet <INetworkNode> validClients) { if (IsConnectionless) { throw new InvalidOperationException("Cannot establish a connection in a connectionless protocol"); } if (Self.Socket == null) { Self.Socket = new Socket(AddressScheme, SocketType.Stream, Protocol); } Self.Socket.Bind(new IPEndPoint(IPAddress.Any, Self.ListeningPort)); Self.Socket.Listen(int.MaxValue); while (true) { Socket newConn = null; if (ListenTimeOut <= 0) { newConn = Self.Socket.Accept(); } else { Thread listenerThread = new Thread(() => newConn = Self.Socket.Accept()); listenerThread.Start(); listenerThread.Join(ListenTimeOut); if (listenerThread.ThreadState != ThreadState.Stopped) { listenerThread.Abort(); } } if (newConn == null) { break; //timed out } else { INetworkNode client = Util.Container.CreateInstance <INetworkNode>(); client.Address = (newConn.RemoteEndPoint as IPEndPoint).Address.GetAddressBytes(); client.Socket = newConn; //check if it is a valid client if (validClients.Contains(client)) { Thread receiverThread = new Thread(new ParameterizedThreadStart(MessageListenerAction)); receiverThread.Start(client); ConnectedClients.Add(client, receiverThread); } else { //disconnect and raise an exception newConn.Disconnect(false); throw new SecurityException($"An unauthorized address: {(newConn.RemoteEndPoint as IPEndPoint).Address} tried to connect to server"); } } } }
private void RemoveClient(INetworkNode Client) { if (lstClients.InvokeRequired) { lstClients.BeginInvoke(new MethodInvoker(delegate() { RemoveClient(Client); })); } else { lstClients.Items.Remove(Client); } }
/// <summary> /// Disconnects a client node from this server /// </summary> /// <param name="client"></param> public void DisconnectNode(INetworkNode client) { if (ConnectedClients.ContainsKey(client)) { if (client.Socket != null && client.Socket.Connected) { client.Socket.Disconnect(false); ConnectedClients[client].Abort(); } ConnectedClients.Remove(client); } }
private static void InternalDecode(INetworkDefinition networkDef, out List <Neuron> neuronList, out List <Connection> connectionList) { // Build a list of neurons. INodeList nodeDefList = networkDef.NodeList; int nodeCount = nodeDefList.Count; neuronList = new List <Neuron>(nodeCount); // A dictionary of neurons keyed on their innovation ID. var neuronDictionary = new Dictionary <uint, Neuron>(nodeCount); // Loop neuron genes. IActivationFunctionLibrary activationFnLib = networkDef.ActivationFnLibrary; for (int i = 0; i < nodeCount; i++) { // Create a Neuron, add it to the neuron list and add an entry into neuronDictionary - // required for next loop. INetworkNode nodeDef = nodeDefList[i]; // Note that we explicitly translate between the two NeuronType enums even though // they define the same types and could therefore be cast from one to the other. // We do this to keep genome and phenome classes completely separated and also to // prevent bugs - e.g. if one of the enums is changed then TranslateNeuronType() will // need to be modified to prevent exceptions at runtime. Otherwise a silent bug may // be introduced. Neuron neuron = new Neuron(nodeDef.Id, nodeDef.NodeType, activationFnLib.GetFunction(nodeDef.ActivationFnId), nodeDef.AuxState); neuronList.Add(neuron); neuronDictionary.Add(nodeDef.Id, neuron); } // Build a list of connections. IConnectionList connectionDefList = networkDef.ConnectionList; int connectionCount = connectionDefList.Count; connectionList = new List <Connection>(connectionCount); // Loop connection genes. for (int i = 0; i < connectionCount; i++) { INetworkConnection connDef = connectionDefList[i]; connectionList.Add( new Connection(neuronDictionary[connDef.SourceNodeId], neuronDictionary[connDef.TargetNodeId], connDef.Weight)); } }
internal override void OnRemoteDisconnected(INetworkNode Remote) { if (RemoteState.Keys.Contains(Remote)) { RemoteState.Remove(Remote); } if (RemoteCommands.Keys.Contains(Remote)) { RemoteCommands.Remove(Remote); } base.OnRemoteDisconnected(Remote); }
/// <summary> /// Close an existing connected socket. /// Derived methods should call the base method at the end of their operation /// to invoke the RemoteDisconnected event and perform final cleanup. /// </summary> public virtual void CloseRemote(INetworkNode Remote) { this.OnRemoteDisconnected(Remote); try { if (Socket != null) { Socket.Disconnect(false); Socket.Dispose(); Socket = null; } } catch { } }
virtual internal void OnNewConnection(INetworkNode Remote) { if (NewConnection != null) { Task.Run(() => { NewConnection?.Invoke(this, new InternetConnectionEventArgs { Local = this, Remote = Remote }); }); } }
internal virtual void OnIncomingMessage(INetworkNode From, byte[] NewMessage) { if ((IncomingMessage == null) || (From == null) || (NewMessage == null) || (NewMessage.Length == 0)) { return; } IncomingMessage?.Invoke(this, new InternetCommunicationEventArgs { Remote = From, Local = this, Direction = CommunicationDirection.Inbound, Message = NewMessage }); }
public void CreateNetworkNodeTest_NullRepository() { Uri uri = new("http://example.com"); IRepository emptyRepo = Factory.CreateRepository(); INetworkNode node = Factory.CreateNetworkNode( uri, null, (a, b) => null, (a, b) => null, Format.JSON, Encoding.Default ); Assert.NotNull(node); }
virtual internal void OnSocketException(INetworkNode Remote, SocketException se) { if (SocketExceptionOccured != null) { Task.Run(() => { SocketExceptionOccured?.Invoke(this, new InternetSocketExceptionEventArgs { Local = this, Remote = Remote, SocketException = se } ); }); } }
virtual internal void OnRemoteDisconnecting(INetworkNode Remote) { if ((RemoteDisconnecting == null) || (Remote == null)) { return; } Task.Run(() => { RemoteDisconnecting?.Invoke(this, new InternetConnectionEventArgs { Local = this, Remote = Remote }); }); }
public void CreateNetworkNodeTest_Server() { Uri uri = new("http://example.com"); INetworkNode node = Factory.CreateNetworkNode( uri, Factory.CreateRepository(), (a, b) => null, (a, b) => null, Format.JSON, Encoding.Default ); Assert.NotNull(node); HttpServer server = node as HttpServer; Assert.NotNull(server); Assert.Equal(uri, server.BaseUri); }
internal virtual void OnBytesReceived(INetworkNode From, int NumberOfBytes) { if ((BytesReceived == null) || (From == null) || (NumberOfBytes <= 0)) { return; } Task.Run(() => { BytesReceived?.Invoke(this, new InternetBytesTransferredEventArgs { Remote = From, Local = this, Direction = CommunicationDirection.Inbound, NumBytes = NumberOfBytes }); }); }
private void OnBytesSent(INetworkNode To, int NumberOfBytes) { if ((BytesSent == null) || (To == null) || (NumberOfBytes <= 0)) { return; } Task.Run(() => { BytesSent?.Invoke(this, new InternetBytesTransferredEventArgs { Remote = To, Local = this, Direction = CommunicationDirection.Outbound, NumBytes = NumberOfBytes }); }); }
private void OnOutgoingMessage(INetworkNode To, byte[] NewMessage) { if ((OutgoingMessage == null) || (To == null) || (NewMessage == null) || (NewMessage.Length == 0)) { return; } Task.Run(() => { OutgoingMessage?.Invoke(this, new InternetCommunicationEventArgs { Remote = To, Local = this, Direction = CommunicationDirection.Outbound, Message = NewMessage }); }); }
/// <summary> /// Add data to the message being formed. Calls OnNewMessage() when a line has been assembled. /// </summary> /// <param name="From">Node message was received from</param> /// <param name="NewMessage">New data to add to message</param> public void AddBytes(INetworkNode From, byte[] NewMessage) { // Add incoming message to buffered message if (IncomingMessages.ContainsKey(From)) { IncomingMessages[From].AddRange(NewMessage); } else { IncomingMessages.Add(From, new List <byte>(NewMessage)); } // If buffered message has an end-of-line terminator, send the line(s) to any listeners byte[] IncomingMessage = IncomingMessages[From].ToArray(); int MessageStart = 0; IEnumerable <int> LinePositions = DataType.FindPackets(IncomingMessage, (uint)NewMessage.Length); if ((LinePositions != null) && (LinePositions.Count() > 0)) { foreach (int LineIndex in LinePositions) { int MessageLength = LineIndex - MessageStart; byte[] Message = new byte[MessageLength]; Buffer.BlockCopy(IncomingMessage, MessageStart, Message, 0, MessageLength); OnMessageReceived(From, Message); MessageStart += MessageLength - 1; } // Preserve any remaining incoming message we may have if ((MessageStart > 0) && (MessageStart < IncomingMessage.Length - 1)) { byte[] Remaining = new byte[IncomingMessage.Length - MessageStart - 1]; Buffer.BlockCopy(IncomingMessage, MessageStart + 1, Remaining, 0, Remaining.Length); IncomingMessages[From] = new List <byte>(Remaining); } else { IncomingMessages.Remove(From); } } }
/// <summary> /// Opens a port for receiving a limited amount of incoming connections in a connection-oriented protocol /// </summary> /// <param name="maxConnections">Maximum number of connections allowed</param> public void Listen(int maxConnections) { if (IsConnectionless) { throw new InvalidOperationException("Cannot establish a connection in a connectionless protocol"); } if (Self.Socket == null) { Self.Socket = new Socket(AddressScheme, SocketType.Stream, Protocol); } Self.Socket.Bind(new IPEndPoint(IPAddress.Any, Self.ListeningPort)); Self.Socket.Listen(maxConnections); while (true) { Socket newConn = null; if (ListenTimeOut <= 0) { newConn = Self.Socket.Accept(); } else { Thread listenerThread = new Thread(() => newConn = Self.Socket.Accept()); listenerThread.Start(); listenerThread.Join(ListenTimeOut); if (listenerThread.ThreadState != ThreadState.Stopped) { listenerThread.Abort(); } } if (newConn == null) { break; //timed out } INetworkNode client = Util.Container.CreateInstance <INetworkNode>(); client.Address = (newConn.RemoteEndPoint as IPEndPoint).Address.GetAddressBytes(); client.Socket = newConn; Thread receiverThread = new Thread(new ParameterizedThreadStart(MessageListenerAction)); receiverThread.Start(client); ConnectedClients.Add(client, receiverThread); } }
/// <summary> /// Generates a route between a source and destination. /// </summary> /// <param name="source"> /// The source node. /// </param> /// <param name="destination"> /// The destination node. /// </param> /// <returns> /// A route between the origin and destination. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if the <see cref="searchType"/> field is invalid. /// </exception> public Route Generate(INetworkNode source, INetworkNode destination) { this.searchType = this.properties.SearchType; if (source.Id == -1) { source = this.properties.NetworkDataProviders[0].GetNodeClosestToPointWithinArea( source, source, 1.0, true); } if (destination.Id == -1) { destination = this.properties.NetworkDataProviders[0].GetNodeClosestToPointWithinArea( destination, destination, 1.0, true); } PTDepthFirstSearch searchAlgorithm; switch (this.searchType) { case SearchType.DFS_Standard: searchAlgorithm = new PTDepthFirstSearch( false, this.properties.NetworkDataProviders[0], source, destination); break; case SearchType.DFS_BiDir: searchAlgorithm = new PTDepthFirstSearch( true, this.properties.NetworkDataProviders[0], source, destination); break; case SearchType.Greedy_Standard: searchAlgorithm = new PTGreedySearch( false, this.properties.NetworkDataProviders[0], source, destination); break; case SearchType.Greedy_BiDir: searchAlgorithm = new PTGreedySearch( true, this.properties.NetworkDataProviders[0], source, destination); break; case SearchType.A_Star_Standard: searchAlgorithm = new PTAStarSearch( false, this.properties.NetworkDataProviders[0], source, destination); break; case SearchType.A_Star_BiDir: searchAlgorithm = new PTAStarSearch( true, this.properties.NetworkDataProviders[0], source, destination); break; case SearchType.RW_Standard: searchAlgorithm = new PTDepthFirstSearch( false, this.properties.NetworkDataProviders[0], source, destination) { UseVisited = false }; break; case SearchType.RW_BiDir: searchAlgorithm = new PTDepthFirstSearch( true, this.properties.NetworkDataProviders[0], source, destination) { UseVisited = false }; break; default: throw new ArgumentOutOfRangeException(); } // PTDepthFirstSearch searchAlgorithm = new PTDepthFirstSearch(properties.Bidirectional,properties.NetworkDataProviders[0],source,destination); INetworkNode[] nodes = searchAlgorithm.Run(); // if (nodes.First() != destination || nodes.Last() != source) // { // throw new Exception("Path is invalid!"); // } // searchAlgorithm.Entropy = 0.0; switch (this.searchType) { case SearchType.DFS_Standard: nodes = nodes.Reverse().ToArray(); break; case SearchType.Greedy_Standard: nodes = nodes.Reverse().ToArray(); break; case SearchType.A_Star_Standard: nodes = nodes.Reverse().ToArray(); break; } // if (!properties.Bidirectional) // { // } // Check for duplicate nodes // foreach (var networkNode in nodes) // { // INetworkNode node = networkNode; // var instances = from n in nodes where n.Id == node.Id select n; // Assert.True(instances.Count() == 1); // } return new Route(-1, nodes); }
/// <summary> /// Initializes a new instance of the <see cref="PTAStarSearch"/> class. /// </summary> /// <param name="depth"> /// The depth. /// </param> /// <param name="bidirectional"> /// The bidirectional. /// </param> /// <param name="provider"> /// The provider. /// </param> /// <param name="origin"> /// The origin. /// </param> /// <param name="goal"> /// The goal. /// </param> public PTAStarSearch( int depth, bool bidirectional, INetworkDataProvider provider, INetworkNode origin, INetworkNode goal) : base(depth, bidirectional, provider, origin, goal) { this.provider = provider; }
public CliqueMatrix(IEnumerable<INetworkNode> nodes, IEnumerable<int> members) : base(nodes) { _members = new SortedSet<int>(members); _representativeNode = base.GetNodeById(_members.First()); }
/// <summary> /// Initializes a new instance of the <see cref="PTAStarSearch"/> class. /// </summary> /// <param name="bidirectional"> /// The bidirectional. /// </param> /// <param name="provider"> /// The provider. /// </param> /// <param name="origin"> /// The origin. /// </param> /// <param name="destination"> /// The destination. /// </param> public PTAStarSearch( bool bidirectional, INetworkDataProvider provider, INetworkNode origin, INetworkNode destination) : base(bidirectional, provider, origin, destination) { this.provider = provider; }
/// <summary> /// Initializes a new instance of the <see cref="PTAStarSearch"/> class. /// </summary> /// <param name="properties"> /// The properties. /// </param> /// <param name="bidirectional"> /// The bidirectional. /// </param> /// <param name="provider"> /// The provider. /// </param> /// <param name="origin"> /// The origin. /// </param> /// <param name="destination"> /// The destination. /// </param> public PTAStarSearch( EvolutionaryProperties properties, bool bidirectional, INetworkDataProvider provider, INetworkNode origin, INetworkNode destination) : base(bidirectional, provider, origin, destination) { this.provider = provider; this.properties = properties; }
/// <summary> /// Create auxiliary data for the specified INetworkNode. /// This version places the node activation function ID into element 0 of the aux data array. /// </summary> protected virtual object[] CreateGraphNodeAuxData(INetworkNode node) { return new object[] {node.ActivationFnId}; }