// // SDLNoticeClient.swift // Tun // // Created by 安礼成 on 2024/5/20. // import Foundation // // SDLanServer.swift // Tun // // Created by 安礼成 on 2024/1/31. // import Foundation import NIOCore import NIOPosix // 处理和sn-server服务器之间的通讯 actor SDLNoticeClient { private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) private let asyncChannel: NIOAsyncChannel, AddressedEnvelope> private let remoteAddress: SocketAddress private let (writeStream, writeContinuation) = AsyncStream.makeStream(of: Data.self, bufferingPolicy: .unbounded) // 启动函数 init() async throws { self.remoteAddress = try! SocketAddress(ipAddress: "127.0.0.1", port: 50195) let bootstrap = DatagramBootstrap(group: self.group) .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) self.asyncChannel = try await bootstrap.bind(host: "0.0.0.0", port: 0) .flatMapThrowing {channel in return try NIOAsyncChannel(wrappingChannelSynchronously: channel, configuration: .init( inboundType: AddressedEnvelope.self, outboundType: AddressedEnvelope.self )) } .get() SDLLogger.log("[SDLNoticeClient] started and listening on: \(self.asyncChannel.channel.localAddress!)", level: .debug) } func start() async throws { try await self.asyncChannel.executeThenClose { inbound, outbound in try await withThrowingTaskGroup(of: Void.self) { group in group.addTask { defer { self.writeContinuation.finish() } for try await message in self.writeStream { let buf = self.asyncChannel.channel.allocator.buffer(bytes: message) let envelope = AddressedEnvelope(remoteAddress: self.remoteAddress, data: buf) try await outbound.write(envelope) } } try await group.waitForAll() } } } // 处理写入逻辑 func send(data: Data) { self.writeContinuation.yield(data) } deinit { try? self.group.syncShutdownGracefully() } }