问题
I have a Cocoa live video program that uses GCDAsyncSocket as the network interface library. There is obvious sluggish when playing the video frames. For example, the time on the video goes almost twice as slow as normal. By inspecting the performance, I found that the GCDAsyncSocket's readDataToLength method is called too sparsely. Below is the log with time stamp:
2012-05-16 11:18:27.054 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.256 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.285 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.452 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.475 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.697 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.726 DVRLibDemo[1181:903] readDataToLength
2012-05-16 11:18:27.856 DVRLibDemo[1181:903] readDataToLength
I set a separate delegate dispatch queue when creating the socket, but it does not help much. The message has a fixed header and I read the header firstly then the payload.
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
DVRConnection *conn = [self getConnectionWithSocket:sock];
//DebugLogInfo(@"Receive raw data: %@ for connection: %d", data, conn.tag);
if (conn != nil && conn.connected)
{
if (tag == TAG_XM_MESSAGE_HEADER)
{
uint32_t bodyLen = [_parser parseMessageHeader:data];
[sock readDataToLength:bodyLen withTimeout:-1 tag:TAG_XM_MESSAGE_PAYLOAD];
}
else if (tag == TAG_XM_MESSAGE_PAYLOAD)
{
[_parser parseMessage:data forConnection:conn device:self];
[sock readDataToLength:XM_MESSAGE_HEADER_LENGTH withTimeout:-1 tag:TAG_XM_MESSAGE_HEADER];
}
}
}
Does anyone have any idea to improve the speed of reading data from socket? thanks!
回答1:
Did you use GCDAsyncUdpSocket
? I think UDP will perform better than TCP (GCDAsyncSocket
) in your case (video transfer). UDP doesn't check for success sending of data. So data is not guaranteed to be delivered, but the upside is it will perform faster. In video or audio data sending, UDP is the preferred choice since some data lost has no significant effect.
Hope this helps :)
回答2:
It turned to be a bug in the parseMessage code. I did not clear the buffer correctly after each read.
来源:https://stackoverflow.com/questions/10611679/gcdasyncsocket-read-data-issue