TcpsocketServer.swift
//// TcpsocketServer.swiftimport Foundationimport CocoaAsyncSocketclass TcpsocketServer:GcdasyncSocket { static let INSTANCE = TcpsocketServer() typealias serverCallBack = (success:Bool,error:NSError?,data:AnyObject?)->() let port:UInt16 = 9001 // tcp clIEnt array var clIEnts = Array<GcdasyncSocket>() func startServer()->Bool{ do{ self.setDelegate(self,delegateQueue: dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,0)) try acceptOnPort(self.port) }catch{ printLog("tcp server accept on port error") printLog(error) return false } return true } func receIEve(data:String!){ dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,0),{()->VoID in printLog(data) TcpsocketServer.INSTANCE.sendAll("this is server "){(success,error,data) in } }) } func sendAll(data:String!,callBack:serverCallBack?){ dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,{()->VoID in let result = data.dataUsingEnCoding(NSUTF8StringEnCoding) print("send msg=") print(result) for clIEnt in self.clIEnts{ clIEnt.writeData(result!,withTimeout: -1,tag: 1) } if callBack == nil{ return } dispatch_async(dispatch_get_main_queue(),{()->VoID in let success:Bool = true callBack!(success:success,error:nil,data:nil) }) }) }}extension TcpsocketServer: GcdasyncSocketDelegate{ func socket(sock: GcdasyncSocket,dIDAcceptNewSocket newSocket: GcdasyncSocket) { //这里sock指服务器的socket,newSocket指客户端的Socket, print("[clIEnt %s:%d connect server]",newSocket.connectedHost,newSocket.connectedPort) //保存客户端的Socket,不然刚连接成功就会自动关闭 self.clIEnts.append(newSocket) //sock只负责连接服务器,newSocket设置成-1,表示一直保持连接 newSocket.readDataWithTimeout(-1,tag: 100) } func socket(clIEnt: GcdasyncSocket,dIDReadData data: NSData,withTag tag: Int) { print("[recIEve clIEnt %s:%d message]",clIEnt.connectedHost,clIEnt.connectedPort) var receIEveStr:String = (Nsstring(data:data,enCoding: NSUTF8StringEnCoding))! as String //去除换行符、回车符1 receIEveStr = receIEveStr.stringByReplacingOccurrencesOfString("\r",withString: "") receIEveStr = receIEveStr.stringByReplacingOccurrencesOfString("\r",withString: "") // 结束删除客户端 if receIEveStr.compare("quit") == NSComparisonResult.OrderedSame { clIEnt.disconnect() let len = self.clIEnts.count for i in 0..<len{ if self.clIEnts[i].connectedUrl == clIEnt.connectedUrl{ self.clIEnts.removeAtIndex(i) } } } self.receIEve(receIEveStr) } func socket(clIEnt: GcdasyncSocket,dIDWriteDataWithTag tag: Int) { print("[send clIEnt %s:%d message]",clIEnt.connectedPort) //服务器每次写数据之前都需要读取一次数据,之后才可以返回数据 clIEnt.readDataWithTimeout(-1,tag: 100) } func socketDIDdisconnect(sock: GcdasyncSocket,withError err: NSError?){ if ((err) != nil) { printLog("断开连接失败") return } print("%s:%d 断开连接",sock.connectedHost,sock.connectedPort) }}
TcpsocketClIEnt.swift
//// TcpsocketClIEnt.swiftimport Foundationclass TcpsocketClIEnt:GcdasyncSocket { static let INSTANCE = TcpsocketClIEnt() typealias clIEntCallBack = (success:Bool,data:AnyObject?)->() func receIEve(data:String!){ dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,{()->VoID in print(data) let t = "this is clIEnt" TcpsocketClIEnt.INSTANCE.send(t){(success,data) in } }) } func send(data:String!,callBack:clIEntCallBack?){ dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,{()->VoID in let result = data.dataUsingEnCoding(NSUTF8StringEnCoding) self.writeData(result!,tag: 1) if callBack == nil{ return } dispatch_async(dispatch_get_main_queue(),data:nil) }) }) } func connect(host:String,port:UInt16)->Bool{ self.setDelegate(self,0)) do{ try self.connectToHost(host,onPort: port) }catch { print("connect %s:%d fail ",host,port) print(error) return false } return true }}extension TcpsocketClIEnt: GcdasyncSocketDelegate{ func socket(clIEnt: GcdasyncSocket,withTag tag: Int) { print("[recIEve server %s:%d message]",enCoding: NSUTF8StringEnCoding))! as String //去除换行符、回车符 receIEveStr = receIEveStr.stringByReplacingOccurrencesOfString("\r",withString: "") // 结束删除客户端 if receIEveStr.compare("quit") == NSComparisonResult.OrderedSame { clIEnt.disconnect() } self.receIEve(receIEveStr) } func socket(clIEnt: GcdasyncSocket,dIDWriteDataWithTag tag: Int) { print("[send server %s:%d message]",tag: 100) } func socket(sock: GcdasyncSocket,dIDConnectToHost host: String,port: UInt16) { print("[connect server %s:%d success]",sock.connectedPort) } func socketDIDdisconnect(sock: GcdasyncSocket,withError err: NSError?){ if ((err) != nil) { print("%s:%d 断开连接失败",sock.connectedPort) return } print("%s:%d 断开连接",sock.connectedPort) }}
调用方式:
server端:
TcpsocketServer.INSTANCE.startServer()
clIEnt端:
TcpsocketClIEnt.INSTANCE.connect("192.168.0.1",port:9001)
总结以上是内存溢出为你收集整理的swift下GCDAsyncSocket的列子全部内容,希望文章能够帮你解决swift下GCDAsyncSocket的列子所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)