本文介绍了Swift中的GCDAsyncSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用基于ELM327芯片的OBD加密狗打开TCP连接。所以我决定使用GCDAsyncSocket库。我写了这段代码,

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)

永远不会运行。

问题出在哪里?

任何人都可以建议我如何传输和接收文字字节串。

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

谢谢

推荐答案

我也遇到了问题,我在下面解决了这个问题。

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

你有使类继承自NSObject。

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

}

以下链接可以帮助您。

这篇关于Swift中的GCDAsyncSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 05:47