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();
    
  • 相关阅读:
    C语言写的trim()函数
    TCP/IP和Socket的关系
    sizeof(数组名)和sizeof(指针)
    字符数组和结束符/0之间的关系
    C语言中二维字符数组的定义和初始化
    异步套接字基础:select函数以及FD_ZERO、FD_SET、FD_CLR、FD_ISSET
    do{...}while(0)的意义和用法
    Mirror--如何在主库上增加文件
    曲苑杂坛--收缩数据库文件
    常用脚本--SQL Server获取OS日志
  • 原文地址:https://www.cnblogs.com/tjhd/p/13952364.html
Copyright © 2011-2022 走看看