自己用的socket连接管理类
pod 'CocoaAsyncSocket'
import Foundation
import CocoaAsyncSocket
typealias ZZWSocketManagerBlock = (_ data:Data) -> Void
typealias ZZWSocketIsAlreadyConnectionedBlock = (_ isconnection:Bool) -> Void
class ZZWSocketManager: NSObject {
var socketIsAlreadyConnectionedBlock:ZZWSocketIsAlreadyConnectionedBlock?
var socketManagerBlock:ZZWSocketManagerBlock?
class var shared: ZZWSocketManager {
return Inner.instance
}
struct Inner {
static let instance = ZZWSocketManager()
}
var socketManger:GCDAsyncSocket?
var sourcedata :Data = Data(capacity: 0)
func setSocketManager() {
socketManger = GCDAsyncSocket(delegate: self , delegateQueue: DispatchQueue.main)
socketManger?.disconnectAfterReadingAndWriting()
}
func tryLinkSocket(_ host:String,_ port:Float) -> Bool{
do {
try self.socketManger?.connect(toHost: host, onPort: UInt16(port), withTimeout: 10)
return true
}catch _ {
socketIsAlreadyConnectionedBlock!(false)
LTLog( "连接失败,请断开链接重新链接设备")
return false
}
}
//writeData写入socket数据一般为字符指令
func writeData(_ writeString:String = "PIC") -> ZZWSocketManager {
let strData = writeString.data(using: String.Encoding.utf8)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) { [weak self] in
self?.socketManger?.write(strData!, withTimeout: 40, tag: 0)
}
return self
}
func afterTimesCheckDidReceiveData() -> ZZWSocketManager {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 180) { [weak self] in
if !socket_receiveImageData {
self?.noticeError("获取数据失败", autoClear: true, autoClearTime: 3)
}
}
return self
}
func socketManagerBlockFunction(socketManagerB:@escaping ZZWSocketManagerBlock){
socketManagerBlock = socketManagerB
}
func socketIsAlreadyConnectionedBlockFunction(socketManagerB:@escaping ZZWSocketIsAlreadyConnectionedBlock){
socketIsAlreadyConnectionedBlock = socketManagerB
}
}
extension ZZWSocketManager : GCDAsyncSocketDelegate,FinalLinkSuccessProtocol{
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
socketIsAlreadyConnectionedBlock!(true)
sock.readData(withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
// LTLog("partialLength %@, \(partialLength)")
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
let error :NSString = "\(String(describing: err))" as NSString
socketIsAlreadyConnectionedBlock!(false)
}
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
sock.readData(withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
DispatchQueue.main.async { [weak self] in
self?.sourcedata.append(data)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.001) {
sock.readData(withTimeout: -1, tag: 0)
}
if data.count < 1{
socketManagerBlock!("NO-data")
}else{
if socketManagerBlock != nil {
socketManagerBlock!(data)
}else{
socketManagerBlock!("NO-data")
}
}
}
}
使用:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
ZZWSocketManager.shared.setSocketManager()
}
//连接socket
ZZWSocketManager.shared.tryLinkSocket(host, port)
//发送信息
ZZWSocketManager.shared.writeData().afterTimesCheckDidReceiveData()
ZZWSocketManager.shared.socketIsAlreadyConnectionedBlockFunction { (isconnection) in
//连接成功/失败 do。。。
}
ZZWSocketManager.shared.socketManagerBlockFunction { [weak self] (data) in
//接收socket数据 do。。。
}
网友评论