var socket = AsyncSocket()socket = AsyncSocket(delegate: self)self.socketConnect()func socketConnect() { do { try socket?.connectToHost("IP Address",onPort: 6968) } catch _ as NSError { } }//MARK: - AsyncSocket Delegates method func onSocket(sock: AsyncSocket!,dIDConnectToHost host: String!,port: UInt16) { print("Connected to host : \(host) with Port : \(port)") let alert:UIAlertController = UIAlertController(Title: "Connected",message: "Host:\(host) ** Port:\(port)",preferredStyle:.Alert) self.presentVIEwController(alert,animated: true,completion: nil) let action:UIAlertAction = UIAlertAction(Title: "Ok",style: .Default) { (UIAlertAction) -> VoID in print("Ok pressed") } alert .addAction(action) let dict = ["iUserID":"100","iRIDeID":"276","type":"clIEnt"] // For clIEnt sIDe var JsonString = Nsstring() do { let data = try NSJsONSerialization.dataWithJsONObject(dict,options: NSJsONWritingOptions.PrettyPrinted) JsonString = Nsstring(data: data,enCoding: NSUTF8StringEnCoding)! }catch let error as NSError { print(error) } let reqData = JsonString.dataUsingEnCoding(NSUTF8StringEnCoding) socket.writeData(reqData,withTimeout: 1.0,tag: 100) } func onSocket(sock: AsyncSocket!,dIDReadPartialDataOfLength partialLength: UInt,tag: Int) { print("Read partial data") } func onSocket(sock: AsyncSocket!,dIDWriteDataWithTag tag: Int) { print("Data write successfully") } func onSocket(sock: AsyncSocket!,dIDReadData data: NSData!,withTag tag: Int) { print("Data read successfully") } func onSocket(sock: AsyncSocket!,willdisconnectWithError err: NSError!) { print("Socket disconnect with error :\(err.description)") } func onSocket(sock: AsyncSocket!,dIDAcceptNewSocket newSocket: AsyncSocket!) { print("Accept new socket") }解决方法 我找到了自己的答案.我错过的是当socket连接到主机时我必须放入readdata线.所以写完之后会调用dIDReadData方法,并且该方法也必须编写我在dIDConnectToHost方法中编写的单行代码.
func socket(sock: GcdasyncSocket!,port: UInt16) { print("Connected to host : \(host) with Port : \(port)") socket.readDataWithTimeout(-1,tag: 0) }func socket(sock: GcdasyncSocket!,withTag tag: Int) { print("Data read successfully") socket.readDataWithTimeout(-1,tag: 0)}总结
以上是内存溢出为你收集整理的如何通过iOS中的套接字从服务器接收数据?全部内容,希望文章能够帮你解决如何通过iOS中的套接字从服务器接收数据?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)