Qt做Tcp数据传输

2020-05-26 16:00:41来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Qt做Tcp数据传输

服务端

void SyncFileServer::createServer()
{
    server = new QTcpServer(this);
    connect(server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));

    bool ok = server -> listen(QHostAddress::Any, 8987);
    qDebug() << "listen: " << ok;
}
void SyncFileServer::newConnectionSlot()
{
    QTcpSocket* socket = server -> nextPendingConnection();
    socketList.append(socket);

    connect(socket, SIGNAL(connected()), this, SLOT(connectedSlot()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorSlot(QAbstractSocket::SocketError)));
}
void SyncFileServer::errorSlot(QAbstractSocket::SocketError socketError)
{
    qDebug() << "error: " << socketError;
    QTcpSocket* s = qobject_cast<QTcpSocket*>(this -> sender());
    socketList.removeOne(s); 
}
void SyncFileServer::readyReadSlot()
{
    QTcpSocket* s = qobject_cast<QTcpSocket*>(this -> sender());

    while (!s -> atEnd())
    {
        QByteArray lineData = s -> readLine();
        ...  // 注意粘包与半包处理
    }
}

客户端

void SyncFileClient::syncFile(QString phoneIP, QString file)
{
    fName = file;
    socket = new QTcpSocket(this);
    socket -> connectToHost(phoneIP, 8987);
    connect(socket, SIGNAL(connected()), this, SLOT(connectedSlot()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorSlot(QAbstractSocket::SocketError)));
    // 以上几个槽函数与服务端处理差不多
}

原文链接:https://www.cnblogs.com/fabric-summoner/p/12963596.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:QTableView与Excel之间的文件打开与保存

下一篇:复习C++语法--基础篇