fix
This commit is contained in:
parent
092959f665
commit
95fe9c4d35
@ -10,6 +10,10 @@ import NetworkExtension
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import Observation
|
import Observation
|
||||||
|
|
||||||
|
enum VPNManagerError: Error {
|
||||||
|
case disconnected
|
||||||
|
}
|
||||||
|
|
||||||
// vpn管理类
|
// vpn管理类
|
||||||
@Observable
|
@Observable
|
||||||
class VPNManager {
|
class VPNManager {
|
||||||
@ -38,10 +42,10 @@ class VPNManager {
|
|||||||
NSLog("enable vpn with options: \(options)")
|
NSLog("enable vpn with options: \(options)")
|
||||||
let manager = try await loadAndCreateProviderManager()
|
let manager = try await loadAndCreateProviderManager()
|
||||||
try await manager.loadFromPreferences()
|
try await manager.loadFromPreferences()
|
||||||
self.manager = manager
|
|
||||||
|
|
||||||
self.addVPNStatusObserver(manager)
|
self.addVPNStatusObserver(manager)
|
||||||
try manager.connection.startVPNTunnel(options: options)
|
try manager.connection.startVPNTunnel(options: options)
|
||||||
|
|
||||||
|
self.manager = manager
|
||||||
}
|
}
|
||||||
|
|
||||||
// 关闭vpn
|
// 关闭vpn
|
||||||
@ -52,6 +56,29 @@ class VPNManager {
|
|||||||
|
|
||||||
try await manager.loadFromPreferences()
|
try await manager.loadFromPreferences()
|
||||||
manager.connection.stopVPNTunnel()
|
manager.connection.stopVPNTunnel()
|
||||||
|
self.manager = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendMessage(_ message: Data) async throws -> Data {
|
||||||
|
guard let session = self.manager?.connection as? NETunnelProviderSession else {
|
||||||
|
throw VPNManagerError.disconnected
|
||||||
|
}
|
||||||
|
|
||||||
|
guard session.status == .connected || session.status == .connecting else {
|
||||||
|
throw VPNManagerError.disconnected
|
||||||
|
}
|
||||||
|
|
||||||
|
return try await withCheckedThrowingContinuation { continuation in
|
||||||
|
do {
|
||||||
|
try session.sendProviderMessage(message) { responseData in
|
||||||
|
// 收到响应,恢复异步挂起点
|
||||||
|
continuation.resume(returning: responseData ?? Data())
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 发送失败,抛出错误
|
||||||
|
continuation.resume(throwing: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Private Methods
|
// MARK: - Private Methods
|
||||||
|
|||||||
@ -110,6 +110,13 @@ class AppContext {
|
|||||||
try await self.vpnManager.enableVpn(options: options)
|
try await self.vpnManager.enableVpn(options: options)
|
||||||
self.networkContext = context
|
self.networkContext = context
|
||||||
self.vpnOptions = options
|
self.vpnOptions = options
|
||||||
|
|
||||||
|
// TODO
|
||||||
|
Task {
|
||||||
|
try await Task.sleep(for: .seconds(5))
|
||||||
|
let resp = try await self.vpnManager.sendMessage("hello vpn".data(using: .utf8)!)
|
||||||
|
NSLog("resp: \(String(data: resp, encoding: .utf8))")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 断开网络连接
|
// 断开网络连接
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user