当使用GCDAsyncSocket
发送长文本字符串时,在接收端多次调用readDataWithTimeOut
,但收到的数据不一致,即收到相同的文本但{{1} } 是不同的。造成这种差异的可能原因是什么?请告诉我,因为我对NSData
知之甚少。
GCDAsyncSocket
答案 0 :(得分:2)
使用此
socket.readDataToData(getNsData(), withTimeout: -1, tag: 1)
而不是
socket.readDataWithTimeout(1, tag: 0)
使用的功能 -
private func getNsData()-> NSData{
return NSData(bytes: "#####", length: 5)
}
并要求服务人员在回复结束时附加“#####”
//本地套接字连接到远程套接字
func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
{
println("Connected to \(host) on port \(p).")
socket.readDataToData(getNsData(), withTimeout: -1, tag: 2)
}
//Some message from remote socket
func socket(socket : GCDAsyncSocket, didReadData data:NSData, withTag tag:UInt16)
{
var response = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
let stringLength = count(response) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - count("#####")
var servResWithoutHash = response.substringToIndex(advance(response.startIndex, substringIndex))
println("Updated response \(servResWithoutHash)")
if let action = getTheCommand(servResWithoutHash){
println("COMMAND == \(action)")
socket.readDataToData(getNsData(), withTimeout: -1, tag: 2)
}
//Notifies when socket gets disconnected
func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) {
println("Socket did disconnect with error \(err?.description)");
}