public void OpenConnection(Action <MessageContext> responseMessageHandler) { using (EneterTrace.Entering()) { if (responseMessageHandler == null) { throw new ArgumentNullException("responseMessageHandler is null."); } using (ThreadLock.Lock(myConnectionManipulatorLock)) { try { mySender = new NamedPipeSender(myInputConnectorAddress, myTimeout); myResponseMessageHandler = responseMessageHandler; myResponseReceiver = new NamedPipeReceiver(myOutputConnectorAddress, 1, myTimeout, mySecurity); myResponseReceiver.StartListening(HandleResponseMessages); // Send the open connection request. object anEncodedMessage = myProtocolFormatter.EncodeOpenConnectionMessage(myOutputConnectorAddress); mySender.SendMessage(anEncodedMessage); } catch { CloseConnection(); throw; } } } }
private void OnRequestMessageReceived(Stream message) { using (EneterTrace.Entering()) { ProtocolMessage aProtocolMessage = myProtocolFormatter.DecodeMessage((Stream)message); if (aProtocolMessage != null) { MessageContext aMessageContext = null; if (aProtocolMessage.MessageType == EProtocolMessageType.OpenConnectionRequest) { if (!string.IsNullOrEmpty(aProtocolMessage.ResponseReceiverId)) { using (ThreadLock.Lock(myConnectedClients)) { if (!myConnectedClients.ContainsKey(aProtocolMessage.ResponseReceiverId)) { NamedPipeSender aClientContext = new NamedPipeSender(aProtocolMessage.ResponseReceiverId, myConnectionTimeout); myConnectedClients[aProtocolMessage.ResponseReceiverId] = aClientContext; } else { EneterTrace.Warning(TracedObject + "could not open connection for client '" + aProtocolMessage.ResponseReceiverId + "' because the client with same id is already connected."); } } } else { EneterTrace.Warning(TracedObject + "could not connect a client because response recevier id was not available in open connection message."); } } else if (aProtocolMessage.MessageType == EProtocolMessageType.CloseConnectionRequest) { if (!string.IsNullOrEmpty(aProtocolMessage.ResponseReceiverId)) { using (ThreadLock.Lock(myConnectedClients)) { NamedPipeSender aClientContext; using (ThreadLock.Lock(myConnectedClients)) { myConnectedClients.TryGetValue(aProtocolMessage.ResponseReceiverId, out aClientContext); if (aClientContext != null) { myConnectedClients.Remove(aProtocolMessage.ResponseReceiverId); } } if (aClientContext != null) { aClientContext.Dispose(); } } } } aMessageContext = new MessageContext(aProtocolMessage, ""); NotifyMessageContext(aMessageContext); } } }
private void CloseConnection(string outputConnectorAddress, NamedPipeSender clientContext) { using (EneterTrace.Entering()) { try { object anEncodedMessage = myProtocolFormatter.EncodeCloseConnectionMessage(outputConnectorAddress); clientContext.SendMessage(anEncodedMessage); } catch (Exception err) { EneterTrace.Warning("failed to send the close message.", err); } clientContext.Dispose(); } }