private static byte[] SendMessageToSocketAndListenToCallback(IPEndPoint source, IPEndPoint destination, byte[] bufferToSend, BytesReceivedDelegate callBack, ProtocolType protocol, byte[] heartbeatMessage, Regex responseFormat, BytesReceivedDelegate heartbeatCallback, bool isSynchronious, bool useSocketPool) { Socket TCPSocket = null; if (useSocketPool) { TCPSocket = CheckIfSocketAlreadyOpen(source, destination); } HeartbeatInfo info = null; try { if (TCPSocket == null) { if (protocol == ProtocolType.Udp) { TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, protocol); } else if (protocol == ProtocolType.Tcp) { TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, protocol); } TCPSocket.Bind(source); if (protocol == ProtocolType.Tcp) { TCPSocket.Connect(destination); if (useSocketPool) { info = new HeartbeatInfo(TCPSocket, heartbeatMessage, responseFormat, heartbeatCallback, 10); info.CallbackDelegate += new BytesReceivedDelegate(CheckIfHeartbeatFailed); lock (openSocketsList) { openSocketsList.Add(info); } } } } // lock (TCPSocket) { if (bufferToSend != null) { if (protocol == ProtocolType.Tcp) { TCPSocket.Send(bufferToSend); } else if (protocol == ProtocolType.Udp) { TCPSocket.SendTo(bufferToSend, destination); } } StateObject state = new StateObject(); if (isSynchronious) { TCPSocket.ReceiveTimeout = 5000; TCPSocket.Receive(state.buffer); if (!useSocketPool) { TCPSocket.Shutdown(SocketShutdown.Both); TCPSocket.Close(); } return(state.buffer); } else if (callBack != null) { state.workSocket = TCPSocket; state.callbackDelegate += callBack; if (info != null) { state.callbackDelegate += info.ProcessMessageReceivedFromSocket; } TCPSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } // } return(null); } catch (Exception ex) { LoggingHelper.LogExceptionInApplicationLog(ex.Source, ex, EventLogEntryType.Error); LoggingHelper.WriteExceptionLogEntry(ex.Source, ex); if (TCPSocket != null && TCPSocket.Connected) { TCPSocket.Shutdown(SocketShutdown.Both); TCPSocket.Close(); } } return(null); }