Github每日精选(第76期):在 Mac 状态栏上显示进程流量的监视器ITraffic-monitor-for-mac
ITraffic-monitor-for-mac
ITraffic-monitor-for-mac 在 Mac 狀態欄上顯示進程流量的監視器,在windows我們的流量可以通過電腦管家或者360進行顯示,在進行網絡編程的時候,這個確實幫了不少忙,但是咱Mac下,顯示網絡狀況就沒有那么方便了,但是我們可以在mac下的監視中找到網絡的監控,但是這個藏得太深,ITraffic-monitor-for-mac就是為了這個需求而生的,ITraffic-monitor-for-mac大部分的代碼采用的是swift語言,工程代碼量并不大,很適合剛開始學習swift語言的同學。
github上的地址在這里。
看看這個軟件,對流量的監控是不是很方便,是不是很windows化。
安裝
macOS 版本應該 >= 10.15,因為項目使用 swiftUI,安裝的方式比較簡單,直接下載app就可以進行mac下的安裝,地址在這里。
如果使用brew:
rew install itraffic更新:
brew update && brew upgrade itraffic我們來看看具體實現的代碼。
代碼分析
能把網絡的監控展示成這么方便,確實是挺好用的,這個最主要的部分是ui的部分和網絡監控部分。
public func startListenNetwork() {let duration = 2let nettopPath = Bundle.main.path(forResource: "nettop-line", ofType: nil)!let task = shellPipe("\"\(nettopPath)\" -P -d -L 0 -J bytes_in,bytes_out -t external -s \(duration) -c") { [self] output intryToMakeAppSleepDeep()let rows = output.components(separatedBy: "|SPLIT|").map { String($0) }var totalInBytes = 0var totalOutBytes = 0let entities: [ProcessEntity] = rows.map { self.parser(text: $0, duration: duration) }.compactMap { entity-> ProcessEntity? inif (entity == nil) {return nil;}totalInBytes += entity?.inBytes ?? 0totalOutBytes += entity?.outBytes ?? 0return entity}DispatchQueue.main.async {self.statusDataModel.update(totalInBytes: totalInBytes, totalOutBytes: totalOutBytes)self.viewModel.updateData(newItems: entities)}}task.resume()}開始進行監控,可以看出,他使用的是nettop-line 這個開源項目,地址在這里。
從nettop-line 中讀回來了網絡信息,再對網絡信息進行處理。
func parser(text: String, duration: Int) -> ProcessEntity? {let item = text.split(separator: ",")if item.count < 3 {return nil}let inBytes = (Int(item[1]) ?? 0) / durationlet outBytes = (Int(item[2]) ?? 0) / durationlet nameAndPid = item[0].split(separator: ".")let pid = nameAndPid[nameAndPid.count - 1]var name = nameAndPidname.removeLast()return ProcessEntity(pid: Int(pid) ?? 0, name: name.joined(separator: "."), inBytes: inBytes, outBytes: outBytes)}@discardableResultfunc shellPipe(_ args: String..., onData: ((String) -> Void)? = nil, didTerminate: (() -> Void)? = nil) -> Process {let task = Process()let pipe = Pipe()task.standardOutput = pipetask.standardInput = Pipe()task.executableURL = URL(fileURLWithPath: "/bin/bash")task.arguments = ["-c"] + argsvar buffer = Data()let outHandle = pipe.fileHandleForReadingvar str = ""var data = Data()outHandle.readabilityHandler = { _ indata = outHandle.availableDataif data.count > 0 {buffer += datastr = String(data: buffer, encoding: String.Encoding.utf8) ?? ""if str.last?.isNewline == true {buffer.removeAll()onData?(str)}outHandle.waitForDataInBackgroundAndNotify() // todo it seems that memory leak here. Not sure how to fix it now.} else {buffer.removeAll()}}outHandle.waitForDataInBackgroundAndNotify()task.terminationHandler = { _ intry? outHandle.close()didTerminate?()}DispatchQueue(label: "shellPipe-\(UUID().uuidString)", qos: .background, attributes: .concurrent).async {do {try task.run()} catch {print("shell pipe executed with error", error)}}return task}shellPipe 中執行命令行,通過命令行獲取網絡的信息。
對ITraffic-monitor-for-mac 的分析就簡單的寫到這里,有興趣的話可以進行他的ui代碼的學習。
總結
以上是生活随笔為你收集整理的Github每日精选(第76期):在 Mac 状态栏上显示进程流量的监视器ITraffic-monitor-for-mac的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魔塔之拯救白娘子~我的第一个VB6+DX
- 下一篇: 573_玩客云安装qbittorrent