/// <summary> /// 关闭所有服务 /// </summary> public void CloseServer() { try { //锁定 lock (Dic_ClientSession) { foreach (var item in Dic_ClientSession) { item.Value.Close(); //关闭每一个连接 } Dic_ClientSession.Clear(); //清除字典 } lock (Dic_ClientThread) { foreach (var item in Dic_ClientThread) { item.Value.Abort();//停止线程 } Dic_ClientThread.Clear(); } Flag_Listen = false; TCPSocket.Shutdown(SocketShutdown.Both);//服务端不能主动关闭连接,需要把监听到的连接逐个关闭 if (TCPSocket != null) { TCPSocket.Close(); } } catch (Exception e) { } }
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); }