GCDAsyncSocket in Swift

£可爱£侵袭症+ 提交于 2019-12-21 05:10:46

问题


I want to open a TCP connection with an OBD dongle based on ELM327 chip. So I have decided to use GCDAsyncSocket library. I wrote this code,

import UIKit
import CocoaAsyncSocket

class ViewController: UIViewController, GCDAsyncSocketDelegate {

    let addr = "192.168.0.10"
    let port:UInt16 = 35000
    var socket:GCDAsyncSocket!

    override func viewDidLoad() {
        super.viewDidLoad()
        socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
        do {
           try socket.connectToHost(addr, onPort: port)
        } catch let e {
           print(e)
        }

    // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       // Dispose of any resources that can be recreated.
    }

    @IBAction func connect(sender: AnyObject) {
      print("Clicked")
    }

   func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
   {
       print("Connected to \(addr) on port \(port).")
   }
}

but when I run the code , the function:

func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)

never gets run.

Where is the problem?

Can anybody advice me about how to transmit and recive literal byte string.

Thanks


回答1:


I also had a problem, and I solve it like below.

You have to make class inherit from NSObject.

import Foundation
import CocoaAsyncSocket

public class MySocket: NSObject, AsyncSocketDelegate {

    var mSocket: AsyncSocket!

    override init() {
        super.init()

        let mSocket = AsyncSocket.init(delegate: self)
        do {
            print("Connecing to socket server...")
            try mSocket.connectToHost("google.com", onPort: 80)
        } catch let error {
            print(error)
        }
    }

    @objc public func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        print("success")
    }

}

Below link can help you.

Implement AsyncSocket callbacks in a swift class




回答2:


FYI, if anyone else is running into the problem where didConnectToHost is not being called and seem to have tried everything else: I realized I was initializing my socket service class in my AppDelegate. When I moved the code elsewhere it worked and the callback was called.



来源:https://stackoverflow.com/questions/35805299/gcdasyncsocket-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!