gpt4 book ai didi

swift - GCDAsyncSocket 不会抛出错误

转载 作者:行者123 更新时间:2023-11-30 13:43:38 29 4
gpt4 key购买 nike

我正在 Mac OS 上的 Swift 上编写简单的 Telnet 客户端。我正在连接到 localhost 上的端口 9052 并发送三个简单的命令。这是我的代码:

import Cocoa
import CocoaAsyncSocket

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

var socket : GCDAsyncSocket!

func applicationDidFinishLaunching(aNotification: NSNotification) {
requestIdentity()
}

func requestIdentity() -> Bool {

socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
let port : UInt16 = 9052
do {
try socket.connectToHost("127.0.0.1", onPort: port, withTimeout: 2.0)
} catch let e {
print("Error \(e) accured while connecting to \(port) on 127.0.0.1")
return false
}
print("connection working")

return true
}

func applicationWillTerminate(aNotification: NSNotification) {

}

func socket(socket : GCDAsyncSocket, didReadData data : NSData, withTag : UInt16) {
let response = String(data: data, encoding: NSUTF8StringEncoding)
print("Got response : \(response)")
}

func socket(socket : GCDAsyncSocket, didConnectToHost host : String, port p: UInt16) {
print("Connected to host \(host) on port \(p)")
var request = "AUTHENTICATE \"1728390\"\n"
var data = request.dataUsingEncoding(NSUTF8StringEncoding)
socket.writeData(data, withTimeout: -1.0, tag: 0)
socket.readDataWithTimeout(-1.0, tag: 0)
request = "SIGNAL NEWNYM\n"
data = request.dataUsingEncoding(NSUTF8StringEncoding)
socket.writeData(data, withTimeout: -1.0, tag: 0)
socket.readDataWithTimeout(-1.0, tag: 0)
request = "QUIT\n"
data = request.dataUsingEncoding(NSUTF8StringEncoding)
socket.writeData(data, withTimeout: -1.0, tag: 0)
}


}

我故意关闭端口 9052,但套接字始终处于“连接”状态 - 它不会抛出任何错误,也不提供任何输出 - 它只是什么都不做。如何解决这个问题?

最佳答案

找到解决办法:连接超时时,

func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!)

被调用。

关于swift - GCDAsyncSocket 不会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251603/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com