public void StopListening() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectedClients)) { foreach (KeyValuePair <string, TClientContext> aClientContext in myConnectedClients) { try { aClientContext.Value.CloseConnection(); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err); } } myConnectedClients.Clear(); } using (ThreadLock.Lock(myListeningManipulatorLock)) { myTcpListenerProvider.StopListening(); myMessageHandler = null; } } }
private void OnRequestMessageReceived(byte[] datagram, EndPoint clientAddress) { using (EneterTrace.Entering()) { if (datagram == null && clientAddress == null) { // The listening got interrupted so nothing to do. return; } // Get the sender IP address. string aClientIp = (clientAddress != null) ? ((IPEndPoint)clientAddress).ToString() : ""; ProtocolMessage aProtocolMessage = myProtocolFormatter.DecodeMessage(datagram); if (aProtocolMessage != null) { aProtocolMessage.ResponseReceiverId = "udp://" + aClientIp + "/"; MessageContext aMessageContext = new MessageContext(aProtocolMessage, aClientIp); try { Action <MessageContext> aMessageHandler = myMessageHandler; if (aMessageHandler != null) { aMessageHandler(aMessageContext); } } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } } }
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 NotifyConnectionRedirected(string clientId, string from, string to) { using (EneterTrace.Entering()) { Action aWaitCallback = () => { using (EneterTrace.Entering()) { if (ConnectionRedirected != null) { try { RedirectEventArgs aMsg = new RedirectEventArgs(clientId, from, to); ConnectionRedirected(this, aMsg); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } } }; EneterThreadPool.QueueUserWorkItem(aWaitCallback); } }
private void OnWebSocketConnectionClosed(object sender, EventArgs e) { using (EneterTrace.Entering()) { Action <MessageContext> aResponseHandler; using (ThreadLock.Lock(myConnectionManipulatorLock)) { aResponseHandler = myResponseMessageHandler; CloseConnection(); } ProtocolMessage aProtocolMessage = new ProtocolMessage(EProtocolMessageType.CloseConnectionRequest, myOutputConnectorAddress, null); MessageContext aMessageContext = new MessageContext(aProtocolMessage, myIpAddress); try { // If the connection closed is not caused that the client called CloseConnection() // but the connection was closed from the service. if (aResponseHandler != null) { aResponseHandler(aMessageContext); } } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } }
public virtual void DetachDuplexInputChannel() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myDuplexInputChannelContextManipulatorLock)) { foreach (TDuplexInputChannelContext aDuplexInputChannelContext in myDuplexInputChannelContexts) { // Go via all connections with clients and close them. CloseConnections(aDuplexInputChannelContext.OpenConnections); try { aDuplexInputChannelContext.AttachedDuplexInputChannel.StopListening(); } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to correctly detach the duplex input channel '" + aDuplexInputChannelContext.AttachedDuplexInputChannel + "'.", err); } aDuplexInputChannelContext.AttachedDuplexInputChannel.ResponseReceiverDisconnected -= OnDuplexInputChannelResponseReceiverDisconnected; aDuplexInputChannelContext.AttachedDuplexInputChannel.MessageReceived -= OnMessageReceived; } myDuplexInputChannelContexts.Clear(); } } }
private String DecodeString(byte[] encodedString, int anEndianEncodingId, int aStringEncodingId) { //using (EneterTrace.Entering()) //{ Encoding anEncoding; if (aStringEncodingId == UTF16 && anEndianEncodingId == BIG_ENDIAN) { anEncoding = Encoding.BigEndianUnicode; } else if (aStringEncodingId == UTF16 && anEndianEncodingId == LITTLE_ENDIAN) { anEncoding = Encoding.Unicode; } else if (aStringEncodingId == UTF8) { anEncoding = Encoding.UTF8; } else { String anErrorMessage = TracedObject + "detected unknown string encoding."; EneterTrace.Warning(anErrorMessage); throw new InvalidOperationException(anErrorMessage); } String aResult = anEncoding.GetString(encodedString, 0, encodedString.Length); return(aResult); //} }
protected override void OnResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { if (BrokerMessageReceived == null) { EneterTrace.Warning(TracedObject + ErrorHandler.NobodySubscribedForMessage); return; } BrokerMessageReceivedEventArgs anEvent = null; try { BrokerMessage aMessage = mySerializer.ForResponseReceiver(e.ResponseReceiverId).Deserialize <BrokerMessage>(e.Message); anEvent = new BrokerMessageReceivedEventArgs(aMessage.MessageTypes[0], aMessage.Message); } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to deserialize the request message.", err); anEvent = new BrokerMessageReceivedEventArgs(err); } try { BrokerMessageReceived(this, anEvent); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } }
protected override void OnResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { if (ResponseReceived == null) { EneterTrace.Warning(TracedObject + ErrorHandler.NobodySubscribedForMessage); return; } if (e.Message is string == false) { string anErrorMessage = TracedObject + "failed to receive the response message because the message is not string."; EneterTrace.Error(anErrorMessage); return; } try { ResponseReceived(this, new StringResponseReceivedEventArgs((string)e.Message)); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } }
// Client opens connection to a particular output. public void OpenOutputConnection(IMessagingSystemFactory messaging, string channelId) { using (EneterTrace.Entering()) { IDuplexOutputChannel anOutputChannel = null; try { using (ThreadLock.Lock(myOutputConnectionLock)) { anOutputChannel = messaging.CreateDuplexOutputChannel(channelId); anOutputChannel.ConnectionClosed += OnConnectionClosed; anOutputChannel.ResponseMessageReceived += OnResponseMessageReceived; anOutputChannel.OpenConnection(); // Connection is successfuly open so it can be stored. myOpenOutputConnections.Add(anOutputChannel); } } catch (Exception err) { EneterTrace.Warning("Failed to open connection to '" + channelId + "'.", err); if (anOutputChannel != null) { anOutputChannel.ConnectionClosed -= OnConnectionClosed; anOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived; } throw; } } }
private void CleanConnection(bool sendMessageFlag) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionManipulatorLock)) { if (myReceiver != null) { myReceiver.StopListening(); myReceiver = null; } if (mySender != null) { if (sendMessageFlag) { try { mySender.SendMessage(x => myProtocolFormatter.EncodeCloseConnectionMessage(myOutputConnectorAddress, x)); } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to send close connection message.", err); } } mySender.Dispose(); mySender = null; } } } }
// Client forwards the message to all output connections. public void ForwardMessage(object message) { using (EneterTrace.Entering()) { IDuplexOutputChannel[] anOutputChannels = null; using (ThreadLock.Lock(myOutputConnectionLock)) { anOutputChannels = myOpenOutputConnections.ToArray(); } // Forward the incoming message to all output channels. foreach (IDuplexOutputChannel anOutputChannel in anOutputChannels) { try { anOutputChannel.SendMessage(message); } catch (Exception err) { // Note: do not rethrow the exception because it woiuld stop forwarding the message to other output channels. EneterTrace.Warning("Failed to send message to '" + anOutputChannel.ChannelId + "'.", err); } } } }
public void StopListening() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectedClients)) { foreach (KeyValuePair<string, NamedPipeSender> aClient in myConnectedClients) { try { CloseConnection(aClient.Key, aClient.Value); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err); } } myConnectedClients.Clear(); } using (ThreadLock.Lock(myListeningManipulatorLock)) { if (myReceiver != null) { myReceiver.StopListening(); myReceiver = null; } myMessageHandler = null; } } }
public static void StopListening(Uri uri) { using (EneterTrace.Entering()) { try { using (ThreadLock.Lock(myListeners)) { // Get all possible listening endpoints. IEnumerable <IPEndPoint> anEndPoints = GetEndPoints(uri); foreach (IPEndPoint anEndPoint in anEndPoints) { // Figure out if exist a host listener for the endpoint. HostListenerBase aHostListener = GetHostListener(anEndPoint); if (aHostListener != null) { // Unregister the path from the host listener. aHostListener.UnregisterListener(uri); // If there is no a path listener then nobody is interested in incoming messages // and the TCP listening can be stopped. if (aHostListener.ExistAnyListener() == false) { myListeners.Remove(aHostListener); } } } } } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to stop listening.", err); } } }
private void DoResponseListening() { using (EneterTrace.Entering()) { myIsListeningToResponses = true; myListeningToResponsesStartedEvent.Set(); try { while (!myStopReceivingRequestedFlag) { ProtocolMessage aProtocolMessage = myProtocolFormatter.DecodeMessage((Stream)myClientStream); if (aProtocolMessage == null) { // The client is disconneced by the service. break; } MessageContext aMessageContext = new MessageContext(aProtocolMessage, myIpAddress); try { myResponseMessageHandler(aMessageContext); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } } catch (Exception err) { // If it is not an exception caused by closing the socket. if (!myStopReceivingRequestedFlag) { EneterTrace.Error(TracedObject + ErrorHandler.FailedInListeningLoop, err); } } myIsListeningToResponses = false; myListeningToResponsesStartedEvent.Reset(); // If the connection was closed from the service. if (!myStopReceivingRequestedFlag) { Action <MessageContext> aResponseHandler = myResponseMessageHandler; CloseConnection(); try { aResponseHandler(null); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } } }
private void HandleRequestMessage(Stream message) { using (EneterTrace.Entering()) { ProtocolMessage aProtocolMessage = myProtocolFormatter.DecodeMessage(message); if (aProtocolMessage != null) { // If it is open connection then add the new connected client. if (aProtocolMessage.MessageType == EProtocolMessageType.OpenConnectionRequest) { if (!string.IsNullOrEmpty(aProtocolMessage.ResponseReceiverId)) { using (ThreadLock.Lock(myConnectedClients)) { if (!myConnectedClients.ContainsKey(aProtocolMessage.ResponseReceiverId)) { TimeSpan aDummyOpenTimeout = TimeSpan.Zero; SharedMemorySender aClientSender = new SharedMemorySender(aProtocolMessage.ResponseReceiverId, false, aDummyOpenTimeout, mySendResponseTimeout, myMaxMessageSize, mySecurity); myConnectedClients[aProtocolMessage.ResponseReceiverId] = aClientSender; } 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."); } } // When a client closes connection with the service. else if (aProtocolMessage.MessageType == EProtocolMessageType.CloseConnectionRequest) { if (!string.IsNullOrEmpty(aProtocolMessage.ResponseReceiverId)) { using (ThreadLock.Lock(myConnectedClients)) { SharedMemorySender aClientSender; myConnectedClients.TryGetValue(aProtocolMessage.ResponseReceiverId, out aClientSender); if (aClientSender != null) { myConnectedClients.Remove(aProtocolMessage.ResponseReceiverId); aClientSender.Dispose(); } } } } MessageContext aMessageContext = new MessageContext(aProtocolMessage, ""); NotifyMessageContext(aMessageContext); } } }
private void ConfigureAdbToForwardCommunication(string portNumber) { using (EneterTrace.Entering()) { string aForwardRequest = string.Format("host:forward:tcp:{0};tcp:{1}", portNumber, portNumber); // Open TCP connection with ADB host. using (TcpClient aTcpClient = new TcpClient()) { aTcpClient.Connect(IPAddress.Loopback, myAdbHostPort); // Encode the message for the ADB host. string anAdbRequest = string.Format("{0}{1}\n", aForwardRequest.Length.ToString("X4"), aForwardRequest); byte[] aRequestContent = Encoding.ASCII.GetBytes(anAdbRequest); aTcpClient.GetStream().Write(aRequestContent, 0, aRequestContent.Length); // Read the response from the ADB host. BinaryReader aReader = new BinaryReader(aTcpClient.GetStream()); byte[] aResponseContent = aReader.ReadBytes(4); string aResponse = Encoding.ASCII.GetString(aResponseContent); // If ADB response indicates something was wrong. if (aResponse.ToUpper() != "OKAY") { // Try to get the reason why it failed. byte[] aLengthBuf = aReader.ReadBytes(4); string aLengthStr = Encoding.ASCII.GetString(aLengthBuf); int aReasonMessageLength = 0; try { aReasonMessageLength = int.Parse(aLengthStr, System.Globalization.NumberStyles.HexNumber); } catch { EneterTrace.Warning(TracedObject + "failed to parse '" + aLengthStr + "' into a number. A hex format of number was expected."); } string aReasonStr = ""; if (aReasonMessageLength > 0) { // Read the content of the error reason message. byte[] aReasonBuf = aReader.ReadBytes(aReasonMessageLength); aReasonStr = Encoding.ASCII.GetString(aReasonBuf); } string anErrorMessage = TracedObject + "failed to configure the ADB host for forwarding the communication. The ADB responded: " + aResponse + " " + aReasonStr; EneterTrace.Error(anErrorMessage); throw new InvalidOperationException(anErrorMessage); } } } }
/// <summary> /// It is called when a message is received from a client connected to this Backup Router. /// The message will be forwarded to the connected service. /// If the sending fails the connection is considered broken it will try to reconnect with the next /// available service and send the message again. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnRequestMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { TConnection aConnection; using (ThreadLock.Lock(myConnectionsLock)) { // If the client does not have associated connection to the service behind the router create it. aConnection = myOpenConnections.FirstOrDefault(x => x.ResponseReceiverId == e.ResponseReceiverId); if (aConnection == null) { aConnection = OpenConnection(e.ResponseReceiverId); myOpenConnections.Add(aConnection); } try { aConnection.DuplexOutputChannel.SendMessage(e.Message); // The message was successfully sent. return; } catch (Exception err) { // Sending of the message failed. Therefore the connection is considered broken. EneterTrace.Warning(TracedObject + "failed to forward the message to " + aConnection.DuplexOutputChannel.ChannelId + ". The connection will be redirected.", err); } // Redirect and try to send again. try { // Close the broken connection. CloseConnection(aConnection); myOpenConnections.Remove(aConnection); // Set next available receiver. SetNextAvailableReceiver(); // Open the new connection. TConnection aNewConnection = OpenConnection(e.ResponseReceiverId); myOpenConnections.Add(aNewConnection); NotifyConnectionRedirected(aNewConnection.ResponseReceiverId, aConnection.DuplexOutputChannel.ChannelId, aNewConnection.DuplexOutputChannel.ChannelId); // Send the message via the new connection. aNewConnection.DuplexOutputChannel.SendMessage(e.Message); } catch (Exception err) { string aMessage = TracedObject + "failed to forward the message after the redirection"; EneterTrace.Error(aMessage, err); throw; } } } }
private void RegisterService(string serviceId, string serviceResponseReceiverId) { using (EneterTrace.Entering()) { bool anIsNewServiceRegistered = false; TServiceContext aServiceContext = null; using (ThreadLock.Lock(myConnectionLock)) { aServiceContext = myConnectedServices.FirstOrDefault(x => x.ServiceId == serviceId || x.ServiceResponseReceiverId == serviceResponseReceiverId); if (aServiceContext == null) { aServiceContext = new TServiceContext(serviceId, serviceResponseReceiverId); myConnectedServices.Add(aServiceContext); anIsNewServiceRegistered = true; } } if (anIsNewServiceRegistered) { if (ServiceRegistered != null) { try { MessageBusServiceEventArgs anEvent = new MessageBusServiceEventArgs(serviceId, serviceResponseReceiverId); ServiceRegistered(this, anEvent); } catch (Exception err) { EneterTrace.Error(TracedObject + ErrorHandler.DetectedException, err); } } } else { // If this connection has registered the same service then do nothing. if (aServiceContext.ServiceId == serviceId && aServiceContext.ServiceResponseReceiverId == serviceResponseReceiverId) { } else if (aServiceContext.ServiceId != serviceId && aServiceContext.ServiceResponseReceiverId == serviceResponseReceiverId) { EneterTrace.Warning("The connection has already registered a different service '" + aServiceContext.ServiceId + "'. Connection will be disconnected."); UnregisterService(serviceResponseReceiverId); } else if (aServiceContext.ServiceId == serviceId && aServiceContext.ServiceResponseReceiverId != serviceResponseReceiverId) { EneterTrace.Warning("Service '" + serviceId + "' is already registered. Connection will be disconnected."); UnregisterService(serviceResponseReceiverId); } } } }
/// <summary> /// Stops the listening. /// </summary> public void StopListening() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myListeningManipulatorLock)) { myStopListeningRequested = true; if (myListener != null) { try { myListener.Stop(); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.IncorrectlyStoppedListening, err); } try { myListener.Close(); } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to close the Http listener.", err); } myListener = null; } if (myListeningThread != null && myListeningThread.ThreadState != ThreadState.Unstarted) { if (!myListeningThread.Join(1000)) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToStopThreadId + myListeningThread.ManagedThreadId.ToString()); try { myListeningThread.Abort(); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToAbortThread, err); } } } myListeningThread = null; myConnectionHandler = null; } } }
private void OnRequestMessageReceived(object sender, TypedRequestReceivedEventArgs <MultiTypedMessage> e) { using (EneterTrace.Entering()) { if (e.ReceivingError != null) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToReceiveMessage, e.ReceivingError); } else { TMessageHandler aMessageHandler; using (ThreadLock.Lock(myMessageHandlers)) { myMessageHandlers.TryGetValue(e.RequestMessage.TypeName, out aMessageHandler); } if (aMessageHandler != null) { object aMessageData; try { aMessageData = mySerializer.ForResponseReceiver(e.ResponseReceiverId).Deserialize(aMessageHandler.Type, e.RequestMessage.MessageData); try { aMessageHandler.Invoke(e.ResponseReceiverId, e.SenderAddress, aMessageData, null); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err); } } catch (Exception err) { try { aMessageHandler.Invoke(e.ResponseReceiverId, e.SenderAddress, null, err); } catch (Exception err2) { EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err2); } } } else { EneterTrace.Warning(TracedObject + ErrorHandler.NobodySubscribedForMessage + " Message type = " + e.RequestMessage.TypeName); } } } }
private void CloseSharedMemory() { using (EneterTrace.Entering()) { try { if (mySharedMemoryCreated != null) { // Close the shared memory. if (!myUseExistingMemoryMappedFile) { // This listener created the memory mapped file so it must indicate the memory mapped file is closed. mySharedMemoryCreated.Reset(); } mySharedMemoryCreated.Dispose(); mySharedMemoryCreated = null; } if (mySharedMemoryFilled != null) { mySharedMemoryFilled.Dispose(); mySharedMemoryFilled = null; } if (mySharedMemoryReady != null) { mySharedMemoryReady.Dispose(); mySharedMemoryReady = null; } if (myMemoryMappedFile != null) { myMemoryMappedFile.Dispose(); myMemoryMappedFile = null; // Delete the mutex ensuring only one listening instance. // After that some other listener can be started. myOnlyListeningInstance.Dispose(); myOnlyListeningInstance = null; } // Release the reference to the callback processing messages. myMessageHandler = null; } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to close shared memory.", err); } } }
public void TraceMessages() { EneterTrace.Info("This is info."); EneterTrace.Warning("This is warning."); EneterTrace.Error("This is error."); // Trace exception try { try { try { TestMethod1(); } catch (Exception err) { throw new Exception("2nd Inner Exception.", err); } } catch (Exception err) { throw new Exception("3th Inner Exception.", err); } } catch (Exception err) { EneterTrace.Info("Info with exception", err); EneterTrace.Warning("Warning with exception", err); EneterTrace.Error("Error with exception", err); } EneterTrace.Error("This is the error with Null", (Exception)null); try { EneterTrace.TraceLog = Console.Out; EneterTrace.Info("Info also to console."); EneterTrace.Warning("Warning also to console."); EneterTrace.Error("Error also to console."); } finally { EneterTrace.TraceLog = null; } // Give some time allowing the trace buffer to flush. Thread.Sleep(300); }
public void DisconnectResponseReceiver(string responseReceiverId) { using (EneterTrace.Entering()) { try { myInputConnector.CloseConnection(responseReceiverId); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err); } } }
// When client received a message from an output connection. private void OnResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { try { myInputChannel.SendResponseMessage(myInputResponseReceiverId, e.Message); } catch (Exception err) { EneterTrace.Warning("Failed to send message via the input channel '" + myInputChannel.ChannelId + "'.", err); } } }
private void SendCloseConnection(string outputConnectorAddress) { using (EneterTrace.Entering()) { try { object anEncodedMessage = myProtocolFormatter.EncodeCloseConnectionMessage(outputConnectorAddress); myMessagingProvider.SendMessage(outputConnectorAddress, anEncodedMessage); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err); } } }
public void StopListening() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myListeningManipulatorLock)) { // Stop the thread listening to messages from the shared memory. myStopListeningRequested = true; try { if (mySharedMemoryFilled != null) { // Make the fake indication just to interrupt waiting in the listening thread. mySharedMemoryFilled.Set(); } } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to indicate the listening thread shall stop.", err); } // Avoid deadlock. if (myListeningThread != null && Thread.CurrentThread.ManagedThreadId != myListeningThread.ManagedThreadId) { if (myListeningThread.ThreadState != ThreadState.Unstarted) { if (!myListeningThread.Join(3000)) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToStopThreadId + myListeningThread.ManagedThreadId.ToString()); try { myListeningThread.Abort(); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToAbortThread, err); } } } } myListeningThread = null; // Close the shared memory. CloseSharedMemory(); } } }
public void CloseConnection() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionManipulatorLock)) { myStopReceivingRequestedFlag = true; myMessageInSendProgress = EMessageInSendProgress.None; if (myTcpClient != null) { // Try to send the frame closing the communication. if (myClientStream != null) { try { // If it was not disconnected by the client then try to send the message the connection was closed. if (myIsListeningToResponses) { // Generate the masking key. byte[] aCloseFrame = WebSocketFormatter.EncodeCloseFrame(null, 1000); myClientStream.Write(aCloseFrame, 0, aCloseFrame.Length); } } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err); } myClientStream.Close(); } try { myTcpClient.Close(); } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to close Tcp connection.", err); } myTcpClient = null; } myReceivedMessages.UnblockProcessingThreads(); } } }
private void CloseConnection(string outputConnectorAddress, SharedMemorySender clientSender) { using (EneterTrace.Entering()) { try { clientSender.SendMessage(x => myProtocolFormatter.EncodeCloseConnectionMessage(outputConnectorAddress, x)); } catch (Exception err) { EneterTrace.Warning("failed to send the close message.", err); } clientSender.Dispose(); } }
public void CloseConnection() { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionManipulatorLock)) { myStopReceivingRequestedFlag = true; if (myClientStream != null) { // Note: do not send a close message in TCP. Just close the socket. myClientStream.Close(); myClientStream = null; } if (myTcpClient != null) { myTcpClient.Close(); myTcpClient = null; } if (myResponseReceiverThread != null && Thread.CurrentThread.ManagedThreadId != myResponseReceiverThread.ManagedThreadId) { if (myResponseReceiverThread.ThreadState != ThreadState.Unstarted) { if (!myResponseReceiverThread.Join(3000)) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToStopThreadId + myResponseReceiverThread.ManagedThreadId); try { myResponseReceiverThread.Abort(); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToAbortThread, err); } } } } myResponseReceiverThread = null; myResponseMessageHandler = null; } } }