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)));
    // 以上几个槽函数与服务端处理差很少
}
相关文章
相关标签/搜索