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();
    
  • 相关阅读:
    ecplise中修改reviewboard密码
    本地上jar命令
    Python面试必须要看的15个问题
    Maven命令行窗口指定settings.xml
    codevs1002搭桥(建图+Prim)
    codevs1099字串变换(Bfs)
    codevs1044四子连棋(Dfs)
    codevs1226倒水问题(Bfs)
    codevs1051单词接龙(栈)
    niop 2014寻找道路
  • 原文地址:https://www.cnblogs.com/tjhd/p/13952364.html
Copyright © 2011-2022 走看看