我正在从Data中读取字节。但是while循环的第一次迭代之后会崩溃。
注意:这不是索引超出范围的问题。
func readData(data: Data)
{
if isPacketRecieved == true
{
SocketManager.shared.connectionOpened()
isPacketRecieved = false
}
// 1
var packetBuffer = Data()
// 2
bufferManager.writeDataToBuffer(data: data)
// 3
while(bufferManager.getUnusedBufferSize() >= MAX_PACKET_SIZE){
// 3.1
packetBuffer.removeAll()
packetBuffer = bufferManager.readDataFromBuffer(size: Int(MAX_PACKET_SIZE))
self.parsePacket(data: packetBuffer)
} // -- while
}
func parsePacket(data: Data){
if data.count == MAX_PACKET_SIZE {
let dataHeader = data[0 ..< 10] ===> // here I am getting crash
let dataBody = data [10 ..< 30]
guard let dataStreamHeader = SocketStream(data: dataHeader) else {return}
guard let dataStreamBody = SocketStream(data: dataBody) else {return}
// ź
guard let exchange = dataStreamHeader.readString(1) else {
return
}
guard let scripCode = dataStreamHeader.readInt() as? Int32 else {
return
}
guard let time = dataStreamHeader.readInt() as? Int32 else {
return
}
guard let type = dataStreamHeader.readString(1) else {
return
}
print("Packet Type :: \(type)")
let responseHeader = ResponseHeaderPacket(exchangeCode: exchange, scripCode: Int(scripCode), time: Int(time), type: type)
var pckt: BroadcasterPacket!
switch type {
case ONE:
var loginReq = sLoginRequest()
let loginData = loginReq.sendAcknowledgementPacket()
manager?.sendAcknowledgementData(data: loginData)
break
case A :
pckt = Packet_A(stream: dataStreamBody, header: responseHeader)
break
case G :
pckt = Packet_G(stream: dataStreamBody, header: responseHeader)
break
case H :
pckt = Packet_H(stream: dataStreamBody, header: responseHeader)
break
case g :
pckt = Packet_g(stream: dataStreamBody, header: responseHeader)
break
case m :
pckt = Packet_m(stream: dataStreamBody, header: responseHeader)
break
case B,C,D,E,F :
pckt = Packet_MarketDepth(stream: dataStreamBody, header: responseHeader)
manageDepthPacket(packet: pckt! as! Packet_MarketDepth)
return
case Z :
pckt = Packet_Z(stream: dataStreamBody, header: responseHeader)
break
case X :
pckt = Packet_X(stream: dataStreamBody, header: responseHeader)
break
default:
break
}
guard let packet = pckt else {
return
}
print("ScropCode :\(packet.header.scripCode)")
quoteObject(packet: packet)
}
}