转自:
Qt实现Socket断线重连机制
用单独的线程接收socket数据,当socket与主机断开时,自动重连。
只贴关键代码
//线程的run函数
void Thread::run()
{
while (!m_boolThreaStopped)
{
if (!m_TcpSocket)
{
m_TcpSocket = new QTcpSocket(this);
connect(m_TcpSocket, SIGNAL(readyRead()), this, SLOT(ReadMsg1()));
connect(m_TcpSocket, SIGNAL(connected()), this, SLOT(Onconnect()));
connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(OnDisConnect()));
}
if (!m_isOkConect)
{
m_TcpSocket->connectToHost(m_QStrSocketIp, m_nSockPort);
//等待连接。。。延时三秒,三秒内连不上返回false
m_isOkConect = m_TcpSocket->waitForConnected(3000);
}
if (!m_isOkConect)
{
continue;
}
if (!m_isOkSetHeader)
{
setHeader(m_TcpSocket, m_QStrToken);
m_isOkSetHeader = m_TcpSocket->waitForBytesWritten(5000);
}
if (!m_isOkSetHeader)
{
continue;
}
m_TcpSocket->waitForReadyRead(3000);
}
m_boolThreaStopped = false;
}
void Thread::OnDisConnect()
{
//socket已断开会进入这个槽函数
//通过把m_isOkConect 设为false,在run线程循环中将重新连接主机
m_isOkConect = false;
//清空半包缓存
m_strToDeBeHandle.clear();
}
加载中,请稍候......