zoukankan      html  css  js  c++  java
  • 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();
    
  • 相关阅读:
    关于SqlServer远程跨库修改数据
    泛型进阶
    .NET泛型初探
    Basic MF
    特征工程
    序列最小最优化算法(SMO)-SVM的求解(续)
    感知器、逻辑回归和SVM的求解
    排序小结
    梯度下降、牛顿法和拉格朗日对偶性
    从决策树到随机森林
  • 原文地址:https://www.cnblogs.com/tjhd/p/13952364.html
Copyright © 2011-2022 走看看