void SendKeepalives() { if (isserver) { foreach (KeyValuePair <IPEndPoint, Level1ConnectionInfo> kvp in connections) { IPEndPoint connection = kvp.Key; Level1ConnectionInfo connectioninfo = kvp.Value; if ((int)DateTime.Now.Subtract(connectioninfo.LastOutgoingPacketTime).TotalMilliseconds > (KeepaliveIntervalSeconds * 1000)) { // LogFile.WriteLine("sending keepalive to " + connection.ToString() ); Send(connection, new byte[] { 0 }); connectioninfo.UpdateLastOutgoingPacketTime(); } } } else { Level1ConnectionInfo connectioninfo = connectiontoserver; if ((int)DateTime.Now.Subtract(connectioninfo.LastOutgoingPacketTime).TotalMilliseconds > (KeepaliveIntervalSeconds * 1000)) { //LogFile.WriteLine("sending keepalive to server" ); Send(new byte[] { 0 }); connectioninfo.UpdateLastOutgoingPacketTime(); } } }
void CheckDisconnections() { if (DateTime.Now.Subtract(lastdisconnectioncheck).TotalMilliseconds < 1000) { return; } lastdisconnectioncheck = DateTime.Now; List <IPEndPoint> disconnected = new List <IPEndPoint>(); //LogFile.WriteLine( Name + " Checking disconnections:" ); foreach (KeyValuePair <IPEndPoint, Level1ConnectionInfo> entry in connections) { IPEndPoint connection = entry.Key; Level1ConnectionInfo connectioninfo = (Level1ConnectionInfo)entry.Value; int timesincelastpacket = (int)(DateTime.Now.Subtract(connectioninfo.LastTimestamp).TotalMilliseconds); // LogFile.WriteLine( Name + " level1connection " + connectioninfo + " time since last packet: " + timesincelastpacket ); if (timesincelastpacket > (ConnectionTimeOutSeconds * 1000)) { disconnected.Add(connection); } } for (int i = 0; i < disconnected.Count; i++) { IPEndPoint connection = disconnected[i]; Level1ConnectionInfo connectioninfo = (Level1ConnectionInfo)connections[connection]; if (Disconnection != null) { Disconnection(this, connectioninfo.connectioninfo); } LogFile.WriteLine(Name + ": level 1 disconnection: " + connectioninfo.EndPoint.ToString()); connections.Remove(connection); } }
// sends received packets up stack void ProcessReceivedPacket(IPEndPoint endpoint, byte[] packetdata) { if (!connections.ContainsKey(endpoint)) { LogFile.WriteLine(Name + ": level 1 newconnection: " + endpoint.ToString()); connections.Add(endpoint, new Level1ConnectionInfo(endpoint, new ConnectionInfo(endpoint, endpoint.Address, endpoint.Port))); } Level1ConnectionInfo level1connectioninfo = connections[endpoint] as Level1ConnectionInfo; level1connectioninfo.LastTimestamp = DateTime.Now; // LogFile.WriteLine( Name + " updating timestamp for connection " + level1connectioninfo ); if (ReceivedPacket != null && packetdata.Length > 1) { ReceivedPacket(this, level1connectioninfo.connectioninfo, packetdata, 0, packetdata.GetLength(0)); } }