public bool Setup(string host, int port)
        {
            Setup();

            if (tcpClient == null)
            {
                try
                {
                    tcpClient = new TcpClient();
                    tcpClient.Connect(host, port);
                    var cryptStream = new CryptedStream(tcpClient.GetStream(), keyPair);
                    if (cryptStream.Setup())
                    {
                        upstreamNode = SetupNode(cryptStream);
                        return(true);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }

                tcpClient.Close();
                tcpClient = null;
                return(false);
            }
            else
            {
                return(true);
            }
        }
        internal NodeSession(CryptedStream stream)
        {
            baseStream = stream;
            bWriter    = new BinaryWriter(stream);
            bReader    = new BinaryReader(stream);

            receiveThread = new Thread(ReceiveLoop);
        }
 private void AcceptLoop()
 {
     while (true)
     {
         var client      = tcpListener.AcceptTcpClient();
         var cryptStream = new CryptedStream(client.GetStream(), keyPair);
         if (cryptStream.Setup(key => TrustedKeys.Contains(key)))
         {
             SetupNode(cryptStream);
         }
     }
 }
        private Node <T> SetupNode(CryptedStream cryptStream)
        {
            var session = new NodeSession <T>(cryptStream);

            session.InternalExceptionOccured += Session_InternalExceptionOccured;
            session.RawMessageReceived       += Session_RawMessageReceived;

            var joinMsg = new NodeJoinedMessage()
            {
                ParentPublicKey = rootNode.PublicKey,
                PublicKey       = session.ReceivedPublicKey,
            };

            foreach (var n in rootNode.Children)
            {
                n.Session.SendMessage(null, joinMsg, null);
            }

            foreach (var n in rootNode.GetAllChildren(true, true))
            {
                session.SendMessage(null, new NodeJoinedMessage()
                {
                    ParentPublicKey = n.Parent.PublicKey,
                    PublicKey       = n.PublicKey,
                }, null);
            }

            var node = new Node <T>(session);

            rootNode.AddChild(node);
            session.StartReadLoop();

            CallNodeJoined(node.PublicKey);

            return(node);
        }