iPhone客户端与服务器间粘包问题解决代码实现案例是本文要介绍的内容,如果您的iPhone App要与服务器交换数据,服务器连续发来两个消息时就可能出现粘包的情况:一号消息准确接收到了,但二号消息接收的不完整。你可以尝试通过CocoaChina论坛的这篇帖子提供的代码解决iPhone客户端与服务器间粘包问题。
- void CNetClient::HandleMsg( char *buf ,int nSize )
- {
- m_nRecvByteCount += nSize;
- if( m_RecvTimer.GetMilliseconds( ) >= 1000 )
- {
- // 保存最近十次的网络包流量大小
- m_RecvByte.AddToTail( m_nRecvByteCount );
- if( m_RecvByte.Count( ) > 10 )
- m_RecvByte.Remove( 0 );
- m_nRecvByteCount = 0;
- m_RecvTimer.Start( );
- }
- m_PackBuffer.Put( buf,nSize);
- int packsize=0;
- int bufsize=m_PackBuffer.TellPut() - m_PackBuffer.TellGet();
- while ( TRUE )
- {
- PACKET_COMMAND *pPack = ( PACKET_COMMAND *)m_PackBuffer.PeekGet( );
- if (pPack)
- {
- // 查看包头是否完整
- if( bufsize<PACKET_HEAD_SIZE)
- {
- break;
- }
- packsize=pPack->GetSize();
- // 查看是否是完整的网络包
- if( bufsize<packsize )
- {
- break;
- }
- if (!packsize || packsize>sizeof(PACKET_COMMAND))
- {
- m_PackBuffer.SeekGet(SEEK_HEAD,0 );
- m_PackBuffer.SeekPut(SEEK_HEAD,0 );
- break;
- }
- PACKET_COMMAND pack;
- m_PackBuffer.Get( &pack, packsize);
- HandlePacket(&pack,packsize);
- bufsize = m_PackBuffer.TellPut() - m_PackBuffer.TellGet();
- if (!bufsize)
- {
- m_PackBuffer.SeekGet(SEEK_HEAD,0);
- m_PackBuffer.SeekPut(SEEK_HEAD,0);
- break;
- }
- }
- }
- if ( m_PackBuffer.TellGet() == m_PackBuffer.TellPut() )
- {
- m_PackBuffer.SeekGet(SEEK_HEAD,0);
- m_PackBuffer.SeekPut(SEEK_HEAD,0);
- }
- }
小结:iPhone客户端与服务器间粘包问题解决代码实现案例的内容介绍完了,希望通过本文的学习能对你有所帮助!