Search code examples
swiftmacoscocoagcdasyncsocket

GCDAsyncSocket doesn't throw error


I'm writing simple Telnet client on Swift for Mac OS. I'm connecting to port 9052 on localhost and sending three simple commands. That's my code:

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)
    }


}

I intentionally close port 9052, but the socket is always "connected" - it doesn't throw any error and doesn't give any output - it just doing nothing. How to fix this?


Solution

  • Found the solution: when the connection times out, the

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

    is called.