QT-TCP

配置

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets network

1
2
3
4
5
6
#include <QTcpSocket>
#include <QTcpServer>
#include <QHostAddress>
#include <QNetworkInterface>
#include <QAbstractSocket>
#include <QIODevice>

客户端

1
2
3
4
5
tcpClient = new QTcpSocket(this);
QHostAddress ip;
quint16 port;

qint64 SendData(const char * data, qint64 len);

连接与断开连接

1
2
3
4
5
6
7
8
9
10
void TcpClient::ConServer()
{
tcpClient->connectToHost(ip,port);
if(tcpClient->waitForConnected(3000))
{
qDebug()<<"connected!";
return;
}else
qDebug()<<"connect failed!";
}
1
2
3
4
5
6
7
8
9
10
11
void TcpClient::DisconServer()
{
qDebug()<<"try to disconnect...";
tcpClient->disconnectFromHost();
if(tcpClient->state() == QAbstractSocket::UnconnectedState
|| tcpClient->waitForDisconnected(3000)){
qDebug()<<"disconnected";
return;
}else
qDebug()<<"disconnect failed!";
}

发送数据

1
2
3
4
5
6
7
8
9
10
qint64 TcpClient::SendData(const char *data, qint64 len)
{
qDebug()<<"send data ...";
qint64 slen = tcpClient->write(data,len);
qDebug()<<"sent "<<slen<< " bytes";
return slen;
}

if(tc->tcpClient->state() == QAbstractSocket::ConnectedState)
tc->SendData(data,data.size());

服务端 (多线程)

1
2
3
TcpSocket *socket;
void ReadData();
void onDisconnectedSlotThread();

初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
TcpServer::TcpServer(QString ip, int port, QObject *parent) : QObject(parent)
{
tcpServer = new QTcpServer(this);
localaddrs = QNetworkInterface::allAddresses();
foreach(QHostAddress ha, localaddrs)
{
qDebug()<<ha.toString();
}
this->ip=ip;
this->port=port;

connect(tcpServer, &QTcpServer::newConnection, this, &TcpServer::NewConnectionSlot);
}

启动

1
2
3
4
5
6
7
8
9
10
bool TcpServer::SvStart()
{
qDebug()<<"try to start tcpserver at"<<ip.toString()<<":"<<port;
bool ok = tcpServer->listen(ip, port);
if(ok)
qDebug("tcp server started!");
else
qDebug("tcp server start failed!");
return ok;
}

新建连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void TcpServer::NewConnectionSlot()
{
qDebug()<<"New Connection Slot coming...";
QTcpSocket *socket = tcpServer->nextPendingConnection();
qDebug()<<"ip:"<<socket->peerAddress().toString()<<":"<<socket->peerPort();


TcpSocket *threadSocket= new TcpSocket();
socketList.append(threadSocket);
threadSocket->setSocketDescriptor(socket->socketDescriptor());
QThread *thread = new QThread(threadSocket);
connect(threadSocket, &QAbstractSocket::disconnected, thread, &QThread::quit);
connect(threadSocket, &QAbstractSocket::disconnected, threadSocket, &TcpSocket::onDisconnectedSlotThread);
connect(threadSocket, &QIODevice::readyRead, threadSocket, &TcpSocket::ReadData);

threadSocket->moveToThread(thread);
thread->start();
}

接收数据

1
2
3
4
5
socket = (TcpSocket*)sender();
while(!socket->atEnd())
{
QByteArray data = this->socket->read(2);
}

断开连接

1
2
3
4
void TcpSocket::onDisconnectedSlotThread()
{
qDebug()<<"onDisconnectedSlotThread.pid:"<<QThread::currentThread();
}

总结

服务端实现 QTcpServer 对象。

客户端和服务端均用 socket 传输数据。