/// <summary> /// Establish this connection /// </summary> public void EstablishConnection() { try { bool connectionAlreadyEstablishing = false; lock (_syncRoot) { if (ConnectionInfo.ConnectionState == ConnectionState.Established) { return; } else if (ConnectionInfo.ConnectionState == ConnectionState.Shutdown) { throw new ConnectionSetupException("Attempting to re-establish a closed connection. Please create a new connection instead."); } else if (ConnectionInfo.ConnectionState == ConnectionState.Establishing) { connectionAlreadyEstablishing = true; } else { ConnectionInfo.NoteStartConnectionEstablish(); } } if (connectionAlreadyEstablishing) { if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Trace("Waiting for connection with " + ConnectionInfo + " to be established."); } if (!WaitForConnectionEstablish(NetworkComms.ConnectionEstablishTimeoutMS)) { throw new ConnectionSetupException("Timeout waiting for connection to be successfully established."); } } else { if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Trace("Establishing new connection with " + ConnectionInfo); } EstablishConnectionSpecific(); if (ConnectionInfo.ConnectionState == ConnectionState.Shutdown) { throw new ConnectionSetupException("Connection was closed immediately after handshake. This can occur if a different thread used and subsequently closed this connection."); } //Once the above has been done the last step is to allow other threads to use the connection ConnectionInfo.NoteCompleteConnectionEstablish(); //Not all connection types will have a known remote network identifier if (ConnectionInfo.NetworkIdentifier != ShortGuid.Empty) { NetworkComms.AddConnectionReferenceByIdentifier(this); } connectionEstablishWait.Set(); if (NetworkComms.LoggingEnabled) { NetworkComms.Logger.Trace(" ... connection successfully established with " + ConnectionInfo); } } } catch (SocketException e) { //If anything goes wrong we close the connection. CloseConnection(true, 43); throw new ConnectionSetupException(e.ToString()); } catch (Exception ex) { //If anything goes wrong we close the connection. CloseConnection(true, 44); //For some odd reason not all SocketExceptions get caught above, so another check here if (ex.GetBaseException().GetType() == typeof(SocketException)) { throw new ConnectionSetupException(ex.ToString()); } else { throw; } } }