• Qt tcp传输简单使用


    pro添加模块与includ头文件

    QT += network
    
    #include <QList>
    #include <QTcpSocket>
    #include <QTcpServer>
    #include <QNetworkInterface>
    

    client端

    socket = new QTcpSocket;
    socket -> connectToHost(serverIP, 8888);
    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)));
    
    socket -> write(data);
    
    qDebug() << socket -> errorString();
    qDebug() << socketError;
    

    server端

    server = new QTcpServer;
    connect(server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
    bool ok = server -> listen(QHostAddress::Any, 8888);
    qDebug() << "listen: " << ok;
    
    void SyncFileServer::newConnectionSlot()
    {
        QTcpSocket* socket = server -> nextPendingConnection();
        socketList.append(socket);
        qDebug() << "new connectd: " << 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)));
    }
    
    QTcpSocket* s = qobject_cast<QTcpSocket*>(this -> sender());
    while (!s -> atEnd())
    {
        QByteArray lineData = s -> readLine();
        // ...
    }
    
    QTcpSocket* s = qobject_cast<QTcpSocket*>(this -> sender());
    socketList.removeAll(s); 
    
    socketList.clear();
    
  • 相关阅读:
    虚拟机网络配置常见问题总结
    Python
    Python
    Python
    Python
    Python
    Python
    MySQL
    MySQL
    MySQL
  • 原文地址:https://www.cnblogs.com/tjhd/p/13952364.html
Copyright © 2020-2023  润新知