71 lines
1.9 KiB
Swift
71 lines
1.9 KiB
Swift
//
|
|
// SDLSuperSession.swift
|
|
// punchnet
|
|
//
|
|
// Created by 安礼成 on 2026/5/27.
|
|
//
|
|
import Foundation
|
|
|
|
final class SDLSuperSession: @unchecked Sendable {
|
|
typealias MessageHandler = @Sendable (SDLSuperMessage) async -> Void
|
|
|
|
private let serverEndpoint: SDLConfiguration.ResolvedServerEndpoint
|
|
private let port: UInt16
|
|
private let onMessage: MessageHandler
|
|
private let client: SDLSuperClient
|
|
|
|
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16, onMessage: @escaping MessageHandler) {
|
|
self.serverEndpoint = serverEndpoint
|
|
self.port = port
|
|
self.onMessage = onMessage
|
|
self.client = SDLSuperClient(serverEndpoint: serverEndpoint, port: port)
|
|
}
|
|
|
|
func run() async throws {
|
|
SDLLogger.log("[SDLSuperSession] start super client: \(self.serverEndpoint.ip)", category: .super)
|
|
|
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
defer {
|
|
group.cancelAll()
|
|
}
|
|
|
|
group.addTask {
|
|
try await self.client.run()
|
|
}
|
|
|
|
group.addTask {
|
|
try await self.readLoop()
|
|
}
|
|
|
|
group.addTask {
|
|
try await self.pingLoop()
|
|
}
|
|
|
|
_ = try await group.next()
|
|
}
|
|
}
|
|
|
|
func stop() async {
|
|
self.client.stop()
|
|
}
|
|
|
|
func send(type: SDLPacketType, data: Data) async {
|
|
self.client.send(type: type, data: data)
|
|
}
|
|
|
|
private func readLoop() async throws {
|
|
for try await message in self.client.messageStream {
|
|
try Task.checkCancellation()
|
|
await self.onMessage(message)
|
|
}
|
|
}
|
|
|
|
private func pingLoop() async throws {
|
|
while true {
|
|
try await Task.sleep(for: .seconds(5))
|
|
try Task.checkCancellation()
|
|
self.client.send(type: .ping, data: Data())
|
|
}
|
|
}
|
|
}
|