forked from wzdnzd/ShadowsocksX-NG-R
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPingClient.swift
More file actions
229 lines (176 loc) · 7.07 KB
/
PingClient.swift
File metadata and controls
229 lines (176 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
//
// PingClient.swift
// ShadowsocksX-R
//
// Created by 称一称 on 16/9/5.
// Copyright © 2016年 qiuyuzhou. All rights reserved.
//
import Foundation
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
public typealias SimplePingClientCallback = (String?)->()
class PingServers:NSObject{
static let instance = PingServers()
let SerMgr = ServerProfileManager.instance
var fastest:String?
var fastest_id : Int=0
// func ping(_ i:Int=0){
// if i == 0{
// fastest_id = 0
// fastest = nil
// }
//
// if i >= SerMgr.profiles.count{
// DispatchQueue.main.async {
// // do the UI update HERE
// let notice = NSUserNotification()
// notice.title = "Ping测试完成!"
// notice.subtitle = "最快的是\(self.SerMgr.profiles[self.fastest_id].remark) \(self.SerMgr.profiles[self.fastest_id].serverHost) \(self.SerMgr.profiles[self.fastest_id].latency!)ms"
// NSUserNotificationCenter.default.deliver(notice)
// }
// return
// }
// let host = self.SerMgr.profiles[i].serverHost
// SimplePingClient.pingHostname(host) { latency in
// DispatchQueue.global().async {
// print("[Ping Result]-\(host) latency is \(latency ?? "fail")")
// self.SerMgr.profiles[i].latency = latency ?? "fail"
//
// if latency != nil {
// if self.fastest == nil{
// self.fastest = latency
// self.fastest_id = i
// }else{
// if Int(latency!) < Int(self.fastest!) {
// self.fastest = latency
// self.fastest_id = i
// }
// }
// DispatchQueue.main.async {
// // do the UI update HERE
// (NSApplication.shared().delegate as! AppDelegate).updateServersMenu()
// (NSApplication.shared().delegate as! AppDelegate).updateRunningModeMenu()
// }
// }
// }
// self.ping(i+1)
// }
// }
func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {
var output : [String] = []
var error : [String] = []
let task = Process()
task.launchPath = cmd
task.arguments = args
let outpipe = Pipe()
task.standardOutput = outpipe
let errpipe = Pipe()
task.standardError = errpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: outdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
output = string.components(separatedBy: "\n")
}
let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: errdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
error = string.components(separatedBy: "\n")
}
task.waitUntilExit()
let status = task.terminationStatus
return (output, error, status)
}
func getlatencyFromString(result:String) -> Double?{
var res = result
if !result.contains("round-trip min/avg/max/stddev =") {
return nil
}
res.removeSubrange(res.range(of: "round-trip min/avg/max/stddev = ")!)
res = String(res.characters.dropLast(3))
res = res.components(separatedBy: "/")[1]
let latency = Double(res)
return latency
}
func pingSingleHost(host:String,completionHandler:@escaping (Double?) -> Void){
DispatchQueue.global(qos: .userInteractive).async {
if let outputString = self.runCommand(cmd: "/sbin/ping", args: "-c","5","-t","5",host).output.last{
completionHandler(self.getlatencyFromString(result: outputString))
}
}
}
func ping(_ i:Int=0){
neverSpeedTestBefore = false
var result:[(Int,Double)] = []
for k in 0..<SerMgr.profiles.count {
let host = self.SerMgr.profiles[k].serverHost
pingSingleHost(host: host, completionHandler: {
if let latency = $0{
self.SerMgr.profiles[k].latency = String(latency)
}
})
}
// after two seconds ,time out
// 这种方式需要改进吧 ?
delay(15){
DispatchQueue.main.async {
for k in 0..<self.SerMgr.profiles.count {
if let late = self.SerMgr.profiles[k].latency{
if let latency = Double(late){
result.append((k,latency))
}
}
}
(NSApplication.shared.delegate as! AppDelegate).updateServersMenu()
(NSApplication.shared.delegate as! AppDelegate).updateRunningModeMenu()
// do the UI update HERE
if let min = result.min(by: {$0.1 < $1.1}){
self.fastest = String(describing: min.1)
self.fastest_id = min.0
let notice = NSUserNotification()
notice.title = "Ping测试完成!"
notice.subtitle = "最快的是\(self.SerMgr.profiles[self.fastest_id].remark) \(self.SerMgr.profiles[self.fastest_id].serverHost) \(self.SerMgr.profiles[self.fastest_id].latency!)ms"
NSUserNotificationCenter.default.deliver(notice)
}
}
}
}
}
typealias Task = (_ cancel : Bool) -> Void
@discardableResult func delay(_ time: TimeInterval, task: @escaping ()->()) -> Task? {
func dispatch_later(block: @escaping ()->()) {
let t = DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: t, execute: block)
}
var closure: (()->Void)? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if let internalClosure = closure {
if (cancel == false) {
DispatchQueue.main.async(execute: internalClosure)
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if let delayedClosure = result {
delayedClosure(false)
}
}
return result;
}
func cancel(_ task: Task?) {
task?(true)
}
var neverSpeedTestBefore:Bool = true