CocoaAsyncSocket server won't start if called from another class

69 views
Skip to first unread message

vahi...@gmail.com

unread,
Feb 5, 2017, 4:12:22 AM2/5/17
to CocoaAsyncSocket

It's a simple socket server.

If I remove Socket class and put serverSocket variable and startSocketServer function inside the ViewController class Socket server will be started to listening.

I check by lsof -i :6000 command to determine if socket started to listening or not.

Whats wrong?!


import UIKit
import CocoaAsyncSocket

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let server = Socket()
        server.startSocketServer()
    }
}

class Socket: NSObject, GCDAsyncSocketDelegate {
    var serverSocket = GCDAsyncSocket()

    /// Staring socket server
    func startSocketServer() {
        self.serverSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
        do {
             try serverSocket.acceptOnInterface(nil, port: 6000)
        } catch {
            print("Port access failed")
        }
    }
}

Arno Gramatke

unread,
Feb 5, 2017, 4:21:42 AM2/5/17
to cocoaasy...@googlegroups.com
You need to retain the server object. It will be dealloc’d after the program leaves viewDidLoad. Therefore the socket will be closed again immediately.

--
You received this message because you are subscribed to the Google Groups "CocoaAsyncSocket" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cocoaasyncsock...@googlegroups.com.
To post to this group, send email to cocoaasy...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cocoaasyncsocket/fda27c7f-1463-4a1e-84e3-043aa7d077a7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

vahi...@gmail.com

unread,
Feb 6, 2017, 1:00:56 AM2/6/17
to CocoaAsyncSocket
I found solution:
I put let server = Socket() Out of ViewDidLoad:
class ViewController: UIViewController {
    let server = Socket()
override func viewDidLoad() { super.viewDidLoad() server.startSocketServer() } }
Reply all
Reply to author
Forward
0 new messages