求助,qtcpsocket 接收数据,不完整
接收端
bool b_res=this->waitForNewConnection(-1);
if(b_res==false)
continue;
//received new connection
QTcpSocket *p_tcpsocket=this->nextPendingConnection();
将p_tcpsocket赋给HandleConnection的mp_connection变量。
int HandleConnection::handle_connection()
{
int n_res=0;
int n_lenrec=0;
while(true)
{
int n_state=mp_connection->state();
qDebug("the state of connection is %d\n",n_state);
if(n_state!=QAbstractSocket::ConnectedState)
break;
bool b_res=mp_connection->waitForReadyRead();
//time out,return
if(!b_res)
{
QString qstr_err=mp_connection->errorString();
QByteArray ba = qstr_err.toLatin1();
char *pc_err=ba.data();
qDebug("the error of waitforreadyread is %s\n",pc_err);
n_res=ERR_TIME_OUT;
break;
}
qint32 n_port=mp_connection->peerPort();
QByteArray bary_port=QByteArray((char*)&n_port,sizeof(qint32));
QHostAddress addr_src=mp_connection->peerAddress();
qint32 n_addr=addr_src.toIPv4Address();
QByteArray bary_addr=QByteArray((char*)&n_addr,sizeof(qint32));
int n_lenavailable=mp_connection->bytesAvailable();
//store data received in bary_datagram
QByteArray bary_datagram=mp_connection->readAll();
if(n_lenavailable!=bary_datagram.size())
qDebug("the length availalbe is not equal to the data received!\n");
n_lenrec+=bary_datagram.size();
//insert source ip and port in the head of bary_datagram;
bary_datagram.insert(0,bary_port);
bary_datagram.insert(0,bary_addr);
HandleMsg *p_handlemsg=new HandleMsg(bary_datagram,mp_dealmsg);
n_res=p_handlemsg->handle_msg();
}
qDebug("the length of data received in all is %d\n",n_lenrec);
if(mp_workthread)
mp_workthread->quit();
return n_res;
}
发送端:
int CmSender::send_data_tcp()
{
QTcpSocket *p_tcpsocket=new QTcpSocket();
p_tcpsocket->abort();
quint16 n_porttmp=mn_port;
p_tcpsocket->connectToHost(maddr_dst,n_porttmp);
bool b_res=p_tcpsocket->waitForConnected();
if(b_res==false)
return ERR_TCP_CONNECT;
//put the whole length of datagram in the fist 8 bytes.
//the whole length include the 8 bytes taken by the length.
quint64 nlen_data=mbary_datagram.size();
quint64 nlen_all=nlen_data+sizeof(quint64);
mbary_datagram.insert(0,(char*)&nlen_all,sizeof(quint64));
quint64 nlen_written=0;
int i=0;
while(nlen_written < nlen_all)
{
qDebug("the num in while is %d\n",++i);
QByteArray bary_send=mbary_datagram.right(nlen_all-nlen_written);
qint64 nlen_send=p_tcpsocket->write(bary_send);
qDebug("the length of data sent is %d\n",nlen_send);
p_tcpsocket->flush();
if(nlen_send==-1)
return ERR_SOCKET_WRITE;
nlen_written+=nlen_send;
}
b_res=p_tcpsocket->waitForBytesWritten();
QString str_error=p_tcpsocket->errorString();
QByteArray ba_error=str_error.toLatin1();
char *pc_err=ba_error.data();
qDebug("the error of send socket is %s\n",pc_err);
if(b_res==false)
return ERR_SOCKET_WAITWRITE;
//sleep(30);
p_tcpsocket->close();
p_tcpsocket->deleteLater();
return 0;
}
发送端发送1M的数据,接收端总共只能收到前500多K,而且最后接收端都报连接已经disconnect。求助各位大神,什么原因?折磨好久了。。。。