GCDAsyncSocket不会抛出错误

时间:2016-02-07 09:04:57

标签: swift macos cocoa gcdasyncsocket

我在Swift for Mac OS上编写简单的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,但是套接字总是“连接” - 它不会抛出任何错误并且不提供任何输出 - 它什么都不做。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

找到解决方案:当连接超时时,

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

被召唤。