private static void Flush(TCPSocket socket) { lock (socket.sendLock) { socket.currentReply?.Trigger(true); socket.currentReply = null; if (socket.state == SocketState.Closed) //|| socket.state == SocketState.Terminated) { return; } if (socket.sendBufferQueue.Count > 0) { var kv = socket.sendBufferQueue.Dequeue(); try { socket.currentReply = kv.Key; socket.sock.BeginSend(kv.Value, 0, kv.Value.Length, SocketFlags.None, socket.sendCallback, socket); } catch (Exception ex) { socket.asyncSending = false; try { kv.Key?.Trigger(false); if (socket.state != SocketState.Closed && !socket.sock.Connected) { // socket.state = SocketState.Closed;// Terminated; socket.Close(); } } catch //(Exception ex2) { socket.Close(); //socket.state = SocketState.Closed;// .Terminated; } Global.Log("TCPSocket", LogType.Error, ex.ToString()); } } else { socket.asyncSending = false; } } }
/// <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 void CloseConnection() { try { socket.Socket.Shutdown(SocketShutdown.Both); socket.Close(); } catch { } try { connection.Socket.Shutdown(SocketShutdown.Both); connection.Close(); } catch { } Program.clientList.Remove(this); }
private void Run() { try { while (true) { Thread.Sleep(1); byte[] data = new byte[socket.Available]; int bytes = 0; try { bytes = socket.Recv(data); } catch (SocketException ex) { if (ex.ErrorCode != 10035) { throw new DisconnectException(); } } catch (Exception) { throw new DisconnectException(); } if (bytes == -1) // Client disconnected { throw new DisconnectException(); } else if (bytes > 0) { packetizer.QueuePackets(data, bytes); int p = packetizer.ProcessPackets(); byte[] actual = null; for (int i = 0; i < p; i++) { actual = packetizer.PopItem(); PyObject obj = Unmarshal.Process <PyObject>(actual); if (obj is PyObjectEx) { // PyException Log.Error("Client", "Got exception from client"); } else { PyPacket packet = new PyPacket(); if (packet.Decode(obj) == false) { Log.Error("Client", "Error decoding PyPacket"); } else { // Get the node ID to send if (packet.dest.type == PyAddress.AddrType.Node) { if (packet.dest.typeID == 1) { packet.dest.typeID = (ulong)nodeID; // We dont want to receive packets in the proxy } if (packet.source.type != PyAddress.AddrType.Client) { Log.Error("Client", string.Format("Wrong source data, expected client but got {0}", packet.source.type)); } Log.Warning("Client", PrettyPrinter.Print(packet.Encode())); if (NodeManager.NotifyNode((int)packet.dest.typeID, obj) == false) { // We cant send the data to the node, what to do? Log.Error("Client", "Trying to send a packet to a non-existing node"); throw new DisconnectException(); } } } } } } } } catch (ThreadAbortException) { } catch (DisconnectException) { } catch (Exception ex) { Log.Error("Client", "Unhandled exception... " + ex.Message); Log.Error("ExceptionHandler", "Stack trace: " + ex.StackTrace); } // We should notify our node about this Log.Error("Client", "Client disconnected"); socket.Close(); ClientManager.RemoveClient(this); }
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); }
public void Run() { try { SendLowLevelVersionExchange(); while (true) { Thread.Sleep(1); byte[] data = null; int bytes = 0; try { data = new byte[socket.Available]; bytes = socket.Recv(data); } catch (SocketException ex) { if (ex.ErrorCode != 10035) { throw new DisconnectException(); } } if (bytes == -1) { // Disconnected throw new DisconnectException(); } else if (bytes > 0) { packetizer.QueuePackets(data, bytes); int p = packetizer.ProcessPackets(); byte[] packet = null; for (int i = 0; i < p; i++) { packet = packetizer.PopItem(); PyObject obj = Unmarshal.Process <PyObject>(packet); PyObject res = Process(obj); if (res != null) { Send(res); } } } } } catch (DisconnectException) { Log.Error("Connection", "Connection closed"); } catch (ThreadAbortException) { } catch (Exception ex) { Log.Error("Connection", "Unhandled exception... " + ex.Message); Log.Error("ExceptionHandler", "Stack trace: " + ex.StackTrace); } Program.waiting.Remove(this); if (forClose) { socket.Close(); } }
private void OnApplicationQuit() { TCPSocket.Close(); }