#include<QtNetwork/QTcpSocket>
#include<QtNetwork/QTcpServer>
1.服务器端
void About::init_tcp() { //server this->tcpServer = new QTcpServer(this); this->tcpSocket = new QTcpSocket(this); if(!tcpServer->listen(QHostAddress::Any,6666)) { qDebug()<<tcpServer->errorString(); close(); return; } connect(tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection())); } void About::acceptConnection() { tcpSocket = tcpServer->nextPendingConnection(); qDebug() << "a client connect!!"; connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(revData())); } void About::tcp_write(const char* data) { tcpSocket->write(data); }
2. 客户端,加入自动重连
void About::init_tcp() { //client QString ip = getIP(); this->tcpSocket = new QTcpSocket(this); tcpSocket->abort(); tcpSocket->connectToHost(ip,6666); connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(revData())); connect(tcpSocket, SIGNAL(connected()), this, SLOT(OnSocketConnected())); connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(OnSocketDisconnected())); connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnSocketError(QAbstractSocket::SocketError))); connect(&m_timer, SIGNAL(timeout()), this, SLOT(ConnectServer())); m_timer.setInterval(3000); m_timer.start(); } QString About::getIP() { QString local_ip; QString str; QList<QHostAddress> list = QNetworkInterface::allAddresses(); foreach (QHostAddress address, list) { if(address.protocol() == QAbstractSocket::IPv4Protocol) { //IPv4地址 if (address.toString().contains("127.0.")) { continue; } local_ip = address.toString(); } } if (local_ip == "127.0.0.1") { qDebug() << "get local ip fail"; return 0; } else { return local_ip; } } void About::OnSocketConnected() { qDebug() << "connected to server"; m_bServerConnected = true; } void About::OnSocketDisconnected() { qDebug() <<"Server disconnected"; m_bServerConnected = false; } void About::OnSocketError(QAbstractSocket::SocketError error) { //emit ShowStatus(m_pTcpSocket->errorString()); qDebug() << tcpSocket->errorString(); } void About::ConnectServer() { if(!m_bServerConnected) { QString ip = getIP(); tcpSocket->connectToHost(ip, 6666); //m_pTcpSocket->waitForConnected(2000);//如果调用这句,界面会卡死 } } void About::revData() { //server QString datas = tcpSocket->readAll(); qDebug()<<datas; } void About::tcp_write(const char* data) { tcpSocket->write(data); }