71 lines
1.8 KiB
Swift
71 lines
1.8 KiB
Swift
//
|
|
// 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 SDLNoticeClientActor {
|
|
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
|
private var channel: Channel?
|
|
private let remoteAddress: SocketAddress
|
|
private let logger: SDLLogger
|
|
|
|
// 启动函数
|
|
init(noticePort: Int, logger: SDLLogger) throws {
|
|
self.logger = logger
|
|
self.remoteAddress = try! SocketAddress(ipAddress: "127.0.0.1", port: noticePort)
|
|
}
|
|
|
|
func start() throws {
|
|
let bootstrap = DatagramBootstrap(group: self.group)
|
|
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
|
.channelInitializer { channel in
|
|
channel.pipeline.addHandler(SDLNoticeClientInboundHandler())
|
|
}
|
|
|
|
self.channel = try bootstrap.bind(host: "0.0.0.0", port: 0).wait()
|
|
self.logger.log("[SDLNoticeClient] started", level: .debug)
|
|
}
|
|
|
|
// 处理写入逻辑
|
|
func send(data: Data) {
|
|
guard let channel = self.channel else {
|
|
return
|
|
}
|
|
|
|
let buf = channel.allocator.buffer(bytes: data)
|
|
let envelope = AddressedEnvelope<ByteBuffer>(remoteAddress: self.remoteAddress, data: buf)
|
|
channel.eventLoop.execute {
|
|
channel.writeAndFlush(envelope, promise: nil)
|
|
}
|
|
}
|
|
|
|
deinit {
|
|
try? self.group.syncShutdownGracefully()
|
|
}
|
|
|
|
}
|
|
|
|
extension SDLNoticeClientActor {
|
|
|
|
private class SDLNoticeClientInboundHandler: ChannelInboundHandler {
|
|
typealias InboundIn = AddressedEnvelope<ByteBuffer>
|
|
}
|
|
|
|
}
|