58 lines
1.4 KiB
Swift
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)
|
|
}
|
|
|
|
}
|