如何通过 iOS 中的套接字从服务器接收数据?
Posted
技术标签:
【中文标题】如何通过 iOS 中的套接字从服务器接收数据?【英文标题】:How to receive data from server through socket in iOS? 【发布时间】:2016-06-08 07:15:42 【问题描述】:我有一个应用程序,我必须使用套接字连接将数据发送到服务器并读取将由服务器发送的数据。我正在使用AsyncSocket
类来写入和读取数据。我成功在服务器上写入数据,服务器可以看到应用程序发送的数据。现在,问题是每当服务器向应用程序发送一些数据时,我如何使用AsyncSocket
类接收这些数据。下面是我的代码。我将委托方法用于读取数据,但它从未调用过。
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")
【问题讨论】:
这个类(委托类)是否继承自NSObject
? ***.com/a/24225381/653513
【参考方案1】:
我已经为自己找到了答案。我错过的是当套接字连接到主机时我必须放置 readdata 线。所以写完之后,这个 didReadData 方法将被调用,并且在那个方法中还必须编写我在 didConnectToHost 方法中编写的单行代码。
func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16)
print("Connected to host : \(host) with Port : \(port)")
socket.readDataWithTimeout(-1, tag: 0)
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int)
print("Data read successfully")
socket.readDataWithTimeout(-1, tag: 0)
【讨论】:
以上是关于如何通过 iOS 中的套接字从服务器接收数据?的主要内容,如果未能解决你的问题,请参考以下文章