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)));
    // 以上幾個槽函數與服務端處理差很少
}
相關文章
相關標籤/搜索