swiftlib_sdlan/Sources/sdlan/SessionManager.swift
2025-07-14 23:24:12 +08:00

58 lines
1.4 KiB
Swift

//
// Session.swift
// sdlan
//
// Created by on 2025/7/14.
//
import Foundation
import NIOCore
struct Session {
// ip,
let dstMac: Data
// nat
let natAddress: SocketAddress
// 使
var lastTimestamp: Int32
init(dstMac: Data, natAddress: SocketAddress) {
self.dstMac = dstMac
self.natAddress = natAddress
self.lastTimestamp = Int32(Date().timeIntervalSince1970)
}
mutating func updateLastTimestamp(_ lastTimestamp: Int32) {
self.lastTimestamp = lastTimestamp
}
}
actor SessionManager {
private var sessions: [Data:Session] = [:]
// session
private let ttl: Int32 = 10
func getSession(toAddress: Data) -> Session? {
let timestamp = Int32(Date().timeIntervalSince1970)
if let session = self.sessions[toAddress] {
if session.lastTimestamp >= timestamp + ttl {
self.sessions[toAddress]?.updateLastTimestamp(timestamp)
return session
} else {
self.sessions.removeValue(forKey: toAddress)
}
}
return nil
}
func addSession(session: Session) {
self.sessions[session.dstMac] = session
}
func removeSession(dstMac: Data) {
self.sessions.removeValue(forKey: dstMac)
}
}