Ejemplo n.º 1
0
        public override ConnectionInfo GetConnectionInfo()
        {
            ConnectionStatus status = ConnectionStatus.Connected;

            if (IsStopped)
            {
                status = HasError ? ConnectionStatus.Error : ConnectionStatus.Idle;
            }
            string user_agent = "";

            if (request.Headers.ContainsKey("USER-AGENT"))
            {
                user_agent = request.Headers["USER-AGENT"];
            }
            return(new ConnectionInfoBuilder()
            {
                ProtocolName = "HTTP Direct",
                Type = ConnectionType.Direct,
                Status = status,
                RemoteName = RemoteEndPoint.ToString(),
                RemoteEndPoint = (IPEndPoint)RemoteEndPoint,
                RemoteHostStatus = IsLocal ? RemoteHostStatus.Local : RemoteHostStatus.None,
                ContentPosition = lastPacket != null ? lastPacket.Position : 0,
                RecvRate = Connection.ReadRate,
                SendRate = Connection.WriteRate,
                AgentName = user_agent,
            }.Build());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initialise the properties of this executor collection.
        /// This involves verfiying  the connection to all the dedicated executors in the database.
        /// </summary>
        public void Init()
        {
            logger.Debug("Init-ing executor collection from db");

            ExecutorStorageView[] executorsStorage = ManagerStorageFactory.ManagerStorage().GetExecutors(TriStateBoolean.True);

            logger.Debug("# of dedicated executors = " + executorsStorage.Length);

            foreach (ExecutorStorageView executorStorage in executorsStorage)
            {
                string         executorId = executorStorage.ExecutorId;
                RemoteEndPoint ep         = new RemoteEndPoint(executorStorage.HostName, executorStorage.Port, RemotingMechanism.TcpBinary);
                MExecutor      me         = new MExecutor(executorId);
                try
                {
                    logger.Debug("Creating a MExecutor and connecting-dedicated to it");
                    me.ConnectDedicated(ep);
                }
                catch (Exception)
                {
                    logger.Debug("Exception while init-ing exec.collection. Continuing with other executors...");
                }
            }

            logger.Debug("Executor collection init done");
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Verify if the executor exists in the database and the remote endpoint host matches the database setting
        /// </summary>
        /// <param name="ep"></param>
        /// <returns></returns>
        private bool VerifyExists(RemoteEndPoint ep)
        {
            bool exists = false;

            try
            {
                logger.Debug("Checking if executor :" + _Id + " exists in db");

                ExecutorStorageView executorStorage = ManagerStorageFactory.ManagerStorage().GetExecutor(_Id);

                bool remoteEndPointNullOrHostIsSameAsExecutor;
                remoteEndPointNullOrHostIsSameAsExecutor =
                    ep == null || (ep != null && executorStorage.HostName == ep.Host);

                if (executorStorage != null && remoteEndPointNullOrHostIsSameAsExecutor)
                {
                    exists = true;
                }

                logger.Debug("Executor :" + _Id + " exists in db=" + exists);
            }
            catch (Exception ex)
            {
                logger.Error("Executor :" + _Id + " invalid id? ", ex);
                throw new InvalidExecutorException("The supplied Executor ID is invalid.", ex);
            }

            return(exists);
        }
Ejemplo n.º 4
0
        public override string ToCSV()
        {
            try
            {
                int    machineEventTypeId = (int)MachineEventType;
                string remoteSocket       = (RemoteEndPoint != null) ? RemoteEndPoint.ToString() : null;
                string resourceURIStr     = (ResourceURI != null) ? ResourceURI.ToString() : null;

                string csvEvent =
                    SERIALISATION_PREFIX + "|" +
                    SessionID + "|" +
                    MonitorServerID + "|" +
                    machineEventTypeId + "|" +
                    Created.ToString(SERIALISATION_DATETIME_FORMAT) + "|" +
                    Username + "|" +
                    remoteSocket + "|" +
                    Message + "|" +
                    ResourceID + "|" +
                    resourceURIStr
                    + END_MESSAGE_DELIMITER;

                return(csvEvent);
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPMonitorMachineEvent ToCSV. " + excp.Message);
                return(null);
            }
        }
 public Task GetAssetsAsync(int scopeId, Checksum[] checksums, string pipeName, CancellationToken cancellationToken)
 => RemoteEndPoint.WriteDataToNamedPipeAsync(
     pipeName,
     (scopeId, checksums),
     (writer, data, cancellationToken) => RemoteHostAssetSerialization.WriteDataAsync(
         writer, _services.GetRequiredService <IRemotableDataService>(), data.scopeId, data.checksums, cancellationToken),
     cancellationToken);
Ejemplo n.º 6
0
        /// <summary>
        /// Returns NetworkIdentifier.GetHashCode() ^ RemoteEndPoint.GetHashCode();
        /// </summary>
        /// <returns>The hashcode for this connection info</returns>
        public override int GetHashCode()
        {
            lock (internalLocker)
            {
                if (!hashCodeCacheSet)
                {
                    if (RemoteEndPoint != null & LocalEndPoint != null)
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ LocalEndPoint.GetHashCode() ^ RemoteEndPoint.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }
                    if (RemoteEndPoint != null)
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ RemoteEndPoint.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }
                    else if (LocalEndPoint != null)
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ LocalEndPoint.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }
                    else
                    {
                        hashCodeCache = NetworkIdentifier.GetHashCode() ^ (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? 1 << 31 : 0);
                    }

                    hashCodeCacheSet = true;
                }

                return(hashCodeCache);
            }
        }
Ejemplo n.º 7
0
        private ServiceHubRemoteHostClient(
            HostWorkspaceServices services,
            HubClient hubClient,
            HostGroup hostGroup,
            Stream stream)
            : base(services)
        {
            var optionService = services.GetRequiredService <IOptionService>();

            if (optionService.GetOption(RemoteHostOptions.EnableConnectionPool))
            {
                int maxPoolConnection = optionService.GetOption(RemoteHostOptions.MaxPoolConnection);

                _connectionPool = new ConnectionPool(
                    connectionFactory: (serviceName, cancellationToken) => CreateConnectionAsync(serviceName, callbackTarget: null, cancellationToken),
                    maxPoolConnection);
            }

            _hubClient = hubClient;
            _hostGroup = hostGroup;

            _endPoint = new RemoteEndPoint(stream, hubClient.Logger, incomingCallTarget: this);
            _endPoint.Disconnected += OnDisconnected;
            _endPoint.UnexpectedExceptionThrown += OnUnexpectedExceptionThrown;
            _endPoint.StartListening();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Use this function in order to connect and authenticate.
        /// </summary>
        /// <param name="key">Your API key.</param>
        public async Task Connect(string key, bool useTls, Action <BaseMessage> received)
        {
            this.Client = new ClientWebSocket();
            Uri url;

            if (useTls)
            {
                url = new Uri($"wss://{RemoteEndPoint.ToString()}");
            }
            else
            {
                url = new Uri($"ws://{RemoteEndPoint.ToString()}");
            }

            await Client.ConnectAsync(url, CancellationToken.None).ConfigureAwait(false);

            this.Transport = new BlackTeaTransport(Client, key, received);
            if (await Transport.Authenticate().ConfigureAwait(false))
            {
                Connected = true;
            }
            else
            {
                throw new InvalidCredentialException("Login rejected.");
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Remote API.
 /// </summary>
 public Task GetAssetsAsync(int scopeId, Checksum[] checksums, string pipeName, CancellationToken cancellationToken)
 => RemoteEndPoint.WriteDataToNamedPipeAsync(
     pipeName,
     (scopeId, checksums),
     (writer, data, cancellationToken) => RemoteHostAssetSerialization.WriteDataAsync(
         writer, _workspaceServices.GetRequiredService <ISolutionAssetStorageProvider>().AssetStorage, _workspaceServices.GetRequiredService <ISerializerService>(), data.scopeId, data.checksums, cancellationToken),
     cancellationToken);
Ejemplo n.º 10
0
        /// <summary>
        /// 查询设备目录请求
        /// </summary>
        /// <returns></returns>
        private SIPRequest QueryItems(SIPEndPoint remoteEndPoint, string remoteSIPId)
        {
            string fromTag = CallProperties.CreateNewTag();
            string toTag   = CallProperties.CreateNewTag();
            int    cSeq    = CallProperties.CreateNewCSeq();
            string callId  = CallProperties.CreateNewCallId();

            SIPURI        remoteUri = new SIPURI(RemoteSIPId, RemoteEndPoint.ToHost(), "");
            SIPURI        localUri  = new SIPURI(LocalSIPId, LocalEndPoint.ToHost(), "");
            SIPFromHeader from      = new SIPFromHeader(null, localUri, fromTag);
            //SIPToHeader to = new SIPToHeader(null, remoteUri, toTag);
            SIPToHeader to         = new SIPToHeader(null, remoteUri, null);
            SIPRequest  catalogReq = Transport.GetRequest(SIPMethodsEnum.MESSAGE, remoteUri);

            catalogReq.Header.From        = from;
            catalogReq.Header.Contact     = null;
            catalogReq.Header.Allow       = null;
            catalogReq.Header.To          = to;
            catalogReq.Header.UserAgent   = UserAgent;
            catalogReq.Header.CSeq        = cSeq;
            catalogReq.Header.CallId      = callId;
            catalogReq.Header.ContentType = "application/MANSCDP+xml";

            return(catalogReq);
        }
        public override string ToCSV()
        {
            try
            {
                string serverEndPointValue = (ServerEndPoint != null) ? ServerEndPoint.ToString() : null;
                string remoteEndPointValue = (RemoteEndPoint != null) ? RemoteEndPoint.ToString() : null;
                string dstEndPointValue    = (DestinationEndPoint != null) ? DestinationEndPoint.ToString() : null;

                string csvEvent =
                    SERIALISATION_PREFIX + "|" +
                    SessionID + "|" +
                    MonitorServerID + "|" +
                    ServerType + "|" +
                    EventType + "|" +
                    Created.ToString(SERIALISATION_DATETIME_FORMAT) + "|" +
                    serverEndPointValue + "|" +
                    remoteEndPointValue + "|" +
                    dstEndPointValue + "|" +
                    Username + "|" +
                    ProcessID + "|" +
                    Message + END_MESSAGE_DELIMITER;

                return(csvEvent);
            }
            catch (Exception excp)
            {
                Logger.Logger.Error("Exception SIPMonitorConsoleEvent ToCSV. ->" + excp.Message);
                return(null);
            }
        }
Ejemplo n.º 12
0
        public override ConnectionInfo GetConnectionInfo()
        {
            ConnectionStatus status = ConnectionStatus.Connected;

            if (IsStopped)
            {
                status = HasError ? ConnectionStatus.Error : ConnectionStatus.Idle;
            }
            string user_agent = "";

            if (request.Headers.ContainsKey("USER-AGENT"))
            {
                user_agent = request.Headers["USER-AGENT"];
            }
            return(new ConnectionInfo(
                       "HTTP Direct",
                       ConnectionType.Direct,
                       status,
                       RemoteEndPoint.ToString(),
                       (IPEndPoint)RemoteEndPoint,
                       IsLocal ? RemoteHostStatus.Local : RemoteHostStatus.None,
                       sentPacket != null ? sentPacket.Position : 0,
                       RecvRate,
                       SendRate,
                       null,
                       null,
                       user_agent));
        }
Ejemplo n.º 13
0
        public override void Connect()
        {
            if (m_InConnecting)
            {
                throw new Exception("The socket is connecting, cannot connect again!");
            }

            if (Client != null)
            {
                throw new Exception("The socket is connected, you neednt' connect again!");
            }

            //If there is a proxy set, connect the proxy server by proxy connector
            if (Proxy != null)
            {
                Proxy.Completed += new EventHandler <ProxyEventArgs>(Proxy_Completed);
                Proxy.Connect(RemoteEndPoint);
                m_InConnecting = true;
                return;
            }

            m_InConnecting = true;

//WindowsPhone doesn't have this property
#if SILVERLIGHT && !WINDOWS_PHONE
            RemoteEndPoint.ConnectAsync(ClientAccessPolicyProtocol, ProcessConnect, null);
#else
            RemoteEndPoint.ConnectAsync(ProcessConnect, null);
#endif
        }
Ejemplo n.º 14
0
        private void OnConstructing(IPEndPoint remote, IPEndPoint local)
        {
            _remote = remote;
            _local  = local;
            created = true;
            try
            {
                if (remote == null)
                {
                    throw new ArgumentNullException(nameof(remote));
                }

                AddressFamily family = remote.AddressFamily;

                if (remote.Port.NotIn(IPEndPoint.MinPort, IPEndPoint.MaxPort))
                {
                    throw new ArgumentOutOfRangeException(nameof(remote.Port), $"The {nameof(remote.Port)} must between {IPEndPoint.MinPort} to {IPEndPoint.MaxPort}.");
                }

                if (remote.Port < 1)
                {
                    throw new ArgumentOutOfRangeException(nameof(remote.Port));
                }

                switch (family)
                {
                case AddressFamily.InterNetwork:
                case AddressFamily.InterNetworkV6:
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(family), $"The AddressFamily only support AddressFamily.InterNetwork and AddressFamily.InterNetworkV6.");
                }

                if (local != null && local.AddressFamily != family)
                {
                    throw new ArgumentException($"The {nameof(local)} and {nameof(family)} not match.");
                }

                Instance = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
                if (local != null && local.Port > 0)
                {
                    Instance.Bind(local);
                }

                this.RemoteEndPoint = remote;
                if (local?.Port > 0)
                {
                    this.LocalEndPoint = local;
                }

                this.Key  = RemoteEndPoint.ToString();
                this.Name = this.Name ?? this.Key;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 连接断开
        /// </summary>
        /// <param name="reason"></param>
        protected override void OnSessionClosed(CloseReason reason)
        {
            this.Log($"远程连接断开 IP-Prot:{RemoteEndPoint.ToString()}、ID:{SessionID}");
            //释放所有的任务
            RemoteCallQueue.ErrorEmpty("远程对象被关闭 原因:" + reason);

            base.OnSessionClosed(reason);
        }
Ejemplo n.º 16
0
        private RpcClient GetClient(RemoteEndPoint endPoint)
        {
            if (endPoint == null)
            {
                throw new ArgumentNullException(nameof(endPoint));
            }

            return(_rpcManagedClients.GetOrAdd(endPoint, NewClient));
        }
        protected override void OnConnect(IOArgs args)
        {
            Console.WriteLine($"Connected to { RemoteEndPoint.ToString()} ");

            //Sending string or Memory<byte> will automaticly create IOArgs with pooled buffer.
            //Send($"HELLO FROM { LocalEndPoint }");

            args.SetBuffer($"HELLO FROM { LocalEndPoint }"); //Copy string to our IOArg's buffer.
            SendArgs(args);
        }
Ejemplo n.º 18
0
 public Session(INetwork network, SocketAsyncEventArgs readEventArg, Socket socket)
 {
     Socket                    = socket;
     Id                        = (uint)RemoteEndPoint.GetHashCode();
     _network                  = network;
     ReadEventArg              = readEventArg;
     _writeEventArg.Completed += WriteComplete;
     Ip                        = RemoteEndPoint.Address;
     ProccessPackets();
 }
Ejemplo n.º 19
0
 public Session(INetBase server, SocketAsyncEventArgs readEventArg, Socket socket)
 {
     Socket                    = socket;
     Id                        = (UInt32)RemoteEndPoint.GetHashCode();
     _server                   = server;
     ReadEventArg              = readEventArg;
     _writeEventArg.Completed += WriteComplete;
     Ip                        = RemoteEndPoint.Address;
     ProccessPackets();
 }
Ejemplo n.º 20
0
 public JsonRpcConnection(
     Workspace workspace,
     TraceSource logger,
     object?callbackTarget,
     Stream serviceStream)
 {
     _workspace       = workspace;
     _serviceEndPoint = new RemoteEndPoint(serviceStream, logger, callbackTarget);
     _serviceEndPoint.UnexpectedExceptionThrown += UnexpectedExceptionThrown;
     _serviceEndPoint.StartListening();
 }
Ejemplo n.º 21
0
            static bool ReportNonFatalWatson(Exception e, CancellationToken cancellationToken)
            {
                // ServiceHub may throw non-cancellation exceptions if it is called after VS started to shut down,
                // even if our cancellation token is signaled. Do not report Watson in such cases to reduce noice.
                if (!cancellationToken.IsCancellationRequested)
                {
                    RemoteEndPoint.ReportNonFatalWatsonWithServiceHubLogs(e, LogMessage);
                }

                return(true);
            }
Ejemplo n.º 22
0
 public override string ToString()
 {
     if (ClientObject?.ClientAccount != null)
     {
         return(ClientObject.ClientAccount.AccountName);
     }
     else
     {
         return(RemoteEndPoint?.ToString());
     }
 }
Ejemplo n.º 23
0
 public void Send()
 {
     if (ParentServer == null)
     {
         return;
     }
     if (mustSend)//only send a packet if we have data to send
     {
         lock (this)
         {
             IBitStream stream = BitStream.Create();                                //create new bitstream
             stream.WriteBasicHeader(15, ConnectionId);                             //write packet type and client id
             stream.WriteExtendedHeader(ServerPacketId, ClientPacketId, (uint)v54); //write packet identifiers
             ServerPacketId++;
             var position = stream.GetPosition();
             stream.SkipBits(16);
             stream.WriteBits(0, 1);//playeractionmanager
             if (GameEvents.Count > 0)
             {
                 stream.WriteBits(1, 1);
                 lock (GameEvents)
                 {
                     List <IGameEvent> events = new List <IGameEvent>();
                     for (int i = 4; i > 0; i--)
                     {
                         IGameEvent gameEvent;
                         if (!GameEvents.TryDequeue(out gameEvent))
                         {
                             break;
                         }
                         events.Add(gameEvent);
                     }
                     GameEventManager.Transmit(stream, events);
                 }
             }
             else
             {
                 stream.WriteBits(0, 1);
             }
             stream.WriteBits(0, 1);//ghostmanager
             var lastPosition = stream.GetPosition();
             stream.SetPosition(position);
             stream.WriteBits(((uint)(lastPosition - 72) / 8), 16);
             stream.SetPosition(lastPosition);
             ParentServer.Send(stream.GetRawBuffer(), RemoteEndPoint);
             Console.WriteLine("[NetworkingClient - " + RemoteEndPoint.ToString() + "] sent packet type " + Convert.ToString(PacketType.Data));
             mustSend = false;
         }
     }
     else
     {
         SendPingRequest();
     }
 }
Ejemplo n.º 24
0
        public RemotableDataJsonRpc(Workspace workspace, TraceSource logger, Stream snapshotServiceStream)
        {
            _workspace            = workspace;
            _remotableDataService = workspace.Services.GetRequiredService <IRemotableDataService>();

            _shutdownCancellationSource = new CancellationTokenSource();

            _endPoint = new RemoteEndPoint(snapshotServiceStream, logger, incomingCallTarget: this);
            _endPoint.UnexpectedExceptionThrown += UnexpectedExceptionThrown;
            _endPoint.Disconnected += OnDisconnected;
            _endPoint.StartListening();
        }
Ejemplo n.º 25
0
 public void Send(string hex)
 {
     lock (this)
     {
         IBitStream stream = new BitStream(DevelopmentHelper.ParseHexString(hex)); //create new bitstream
         stream.WriteBasicHeader(15, ConnectionId);                                //write packet type and client id
         stream.WriteExtendedHeader(ServerPacketId, ClientPacketId, (uint)v54);    //write packet identifiers
         ServerPacketId++;
         ParentServer.Send(stream.GetRawBuffer(), RemoteEndPoint);
         Console.WriteLine("[NetworkingClient - " + RemoteEndPoint.ToString() + "] sent packet type " + Convert.ToString(PacketType.Data));
     }
 }
Ejemplo n.º 26
0
 public override ConnectionInfo GetConnectionInfo()
 {
     return(new ConnectionInfoBuilder {
         ProtocolName = "No Protocol Matched",
         Type = ConnectionType.Metadata,
         Status = ConnectionStatus.Connected,
         RemoteName = RemoteEndPoint.ToString(),
         RemoteEndPoint = (IPEndPoint)RemoteEndPoint,
         RemoteHostStatus = IsLocal ? RemoteHostStatus.Local : RemoteHostStatus.None,
         RecvRate = Connection.ReadRate,
         SendRate = Connection.WriteRate,
         AgentName = request.Headers["USER-AGENT"],
     }.Build());
 }
Ejemplo n.º 27
0
        public override ConnectionInfo GetConnectionInfo()
        {
            ConnectionStatus status = ConnectionStatus.Connected;

            if (IsStopped)
            {
                status = HasError ? ConnectionStatus.Error : ConnectionStatus.Idle;
            }
            var host_status = RemoteHostStatus.None;

            if (IsLocal)
            {
                host_status |= RemoteHostStatus.Local;
            }
            var relay_count  = 0;
            var direct_count = 0;

            if (Downhost != null)
            {
                if (Downhost.IsFirewalled)
                {
                    host_status |= RemoteHostStatus.Firewalled;
                }
                if (Downhost.IsRelayFull)
                {
                    host_status |= RemoteHostStatus.RelayFull;
                }
                if (Downhost.IsReceiving)
                {
                    host_status |= RemoteHostStatus.Receiving;
                }
                relay_count  = Downhost.RelayCount;
                direct_count = Downhost.DirectCount;
            }
            return(new ConnectionInfoBuilder {
                ProtocolName = "PCP Relay",
                Type = ConnectionType.Relay,
                Status = status,
                RemoteName = RemoteEndPoint.ToString(),
                RemoteEndPoint = (IPEndPoint)RemoteEndPoint,
                RemoteHostStatus = host_status,
                RemoteSessionID = Downhost?.SessionID,
                ContentPosition = lastPosition,
                RecvRate = Connection.ReadRate,
                SendRate = Connection.WriteRate,
                LocalRelays = relay_count,
                LocalDirects = direct_count,
                AgentName = this.UserAgent ?? "",
            }.Build());
        }
Ejemplo n.º 28
0
        private InProcRemoteHostClient(
            HostWorkspaceServices services,
            InProcRemoteServices inprocServices,
            Stream stream)
        {
            _workspaceServices = services;
            _logger            = new TraceSource("Default");

            _inprocServices = inprocServices;

            _endPoint = new RemoteEndPoint(stream, _logger, incomingCallTarget: this);
            _endPoint.Disconnected += OnDisconnected;
            _endPoint.StartListening();
        }
Ejemplo n.º 29
0
            public DataPoint(
                ReferenceCodeLensProvider owner,
                ICodeLensCallbackService callbackService,
                CodeLensDescriptor descriptor,
                Stream stream)
            {
                _owner           = owner;
                _callbackService = callbackService;

                Descriptor = descriptor;

                _endPoint = new RemoteEndPoint(stream, owner._client.Logger, new RoslynCallbackTarget(Invalidate));
                _endPoint.StartListening();
            }
Ejemplo n.º 30
0
        /// <summary>
        /// Returns a string containing suitable information about this connection
        /// </summary>
        /// <returns>A string containing suitable information about this connection</returns>
        public override string ToString()
        {
            //Add a useful connection state identifier
            string connectionStateIdentifier;

            switch (ConnectionState)
            {
            case ConnectionState.Undefined:
                connectionStateIdentifier = "U";
                break;

            case ConnectionState.Establishing:
                connectionStateIdentifier = "I";
                break;

            case ConnectionState.Established:
                connectionStateIdentifier = "E";
                break;

            case ConnectionState.Shutdown:
                connectionStateIdentifier = "S";
                break;

            default:
                throw new Exception("Unexpected connection state.");
            }

            string returnString = "[" + ConnectionType.ToString() + "-" + (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? "E" : "D") + "-" + connectionStateIdentifier + "] ";

            if (RemoteEndPoint != null && LocalEndPoint != null)
            {
                returnString += LocalEndPoint.ToString() + " -> " + RemoteEndPoint.ToString();
            }
            else if (RemoteEndPoint != null)
            {
                returnString += "Local -> " + RemoteEndPoint.ToString();
            }
            else if (LocalEndPoint != null)
            {
                returnString += LocalEndPoint.ToString() + " " + (IsConnectable ? "Connectable" : "NotConnectable");
            }

            if (NetworkIdentifier != ShortGuid.Empty)
            {
                returnString += " (" + NetworkIdentifier + ")";
            }

            return(returnString.Trim());
        }