Qt network communication

Qt provides a powerful set of network communication functions that can be used for network communication in applications. The following are the main components and functions of Qt network communication:

  1. QNetworkAccessManager:

  2. Is the network access manager in Qt for sending HTTP requests and receiving responses. It supports HTTP request methods such as GET, POST, PUT, DELETE, etc., and provides rich functions, such as setting request headers, handling redirection, handling authentication, etc.

  3. Interface Description:

  4. 构造函数:
    QNetworkAccessManager(parent: QObject = None):构造一个 QNetworkAccessManager 实例。
    parent:可选参数,指定父对象,用于内存管理。
    方法:
    get(request: QNetworkRequest) -> QNetworkReply:发送一个 GET 请求并返回响应的 QNetworkReply 对象。
    
    request:QNetworkRequest 对象,包含请求的 URL、请求头等信息。
    post(request: QNetworkRequest, data: QByteArray) -> QNetworkReply:发送一个 POST 请求并返回响应的 QNetworkReply 对象。
    
    request:QNetworkRequest 对象,包含请求的 URL、请求头等信息。
    data:包含要发送的数据的 QByteArray 对象。
    put(request: QNetworkRequest, data: QByteArray) -> QNetworkReply:发送一个 PUT 请求并返回响应的 QNetworkReply 对象。
    
    request:QNetworkRequest 对象,包含请求的 URL、请求头等信息。
    data:包含要发送的数据的 QByteArray 对象。
    deleteResource(request: QNetworkRequest) -> QNetworkReply:发送一个 DELETE 请求并返回响应的 QNetworkReply 对象。
    
    request:QNetworkRequest 对象,包含请求的 URL、请求头等信息。
    head(request: QNetworkRequest) -> QNetworkReply:发送一个 HEAD 请求并返回响应的 QNetworkReply 对象。
    
    request:QNetworkRequest 对象,包含请求的 URL、请求头等信息。
    createRequest(op: QNetworkAccessManager.Operation, request: QNetworkRequest, outgoingData: QIODevice = None) -> QNetworkReply:创建一个自定义的网络请求,并返回对应的 QNetworkReply 对象。
    
    op:QNetworkAccessManager.Operation 枚举,表示请求的操作类型,如 GET、POST、PUT、DELETE 等。
    request:QNetworkRequest 对象,包含请求的 URL、请求头等信息。
    outgoingData:可选参数,用于发送数据的 QIODevice 对象。
    setConfiguration(config: QNetworkConfiguration):设置网络配置,用于特定网络访问的设置。
    
    config:QNetworkConfiguration 对象,包含特定的网络配置。
    configuration() -> QNetworkConfiguration:获取当前网络配置。
    
    返回:QNetworkConfiguration 对象,表示当前网络配置。
    cookieJar() -> QNetworkCookieJar:获取当前的 Cookie 管理器。
    
    返回:QNetworkCookieJar 对象,表示当前的 Cookie 管理器。
    setCookieJar(cookieJar: QNetworkCookieJar):设置 Cookie 管理器。
    
    cookieJar:QNetworkCookieJar 对象,用于管理 Cookie。
    setProxyFactory(factory: QNetworkProxyFactory):设置代理工厂,用于处理网络请求的代理设置。
    
    factory:QNetworkProxyFactory 对象,用于处理代理设置。
    信号:
    QNetworkAccessManager 也提供了一些信号,用于通知网络请求的状态和进度。
    
    authenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator):当服务器要求身份验证时触发的信号。
    encrypted(QNetworkReply *reply):在通过 SSL 加密连接时触发的信号。
    finished(QNetworkReply *reply):当一个网络请求完成时触发的信号。
    networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible):当网络可用性状态发生变化时触发的信号。
    preSharedKeyAuthenticationRequired(QNetworkReply *reply, QSslPreSharedKeyAuthenticator *authenticator):当服务器要求预共享密钥验证时触发的信号。
    proxyAuthenticationRequired(QNetworkProxy proxy, QAuthenticator *authenticator):当使用代理服务器时,要求代理服务器身份验证时触发的信号。
    以上就是 QNetworkAccessManager 类的主要接口说明,它提供了便捷的方法来处理网络请求和响应,并且通过信号提供了网络状态和进度的反馈。注意在使用 QNetworkAccessManager 进行网络访问时,要确保适当地处理身份验证、代理设置和错误处理等方面的逻辑。

    Use the code:

  5. #include <QCoreApplication>
    #include <QtNetwork/QNetworkAccessManager>
    #include <QtNetwork/QNetworkRequest>
    #include <QtNetwork/QNetworkReply>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        // 创建QNetworkAccessManager对象
        QNetworkAccessManager manager;
    
        // 创建QNetworkRequest对象,并设置请求的URL
        QNetworkRequest request;
        request.setUrl(QUrl("https://api.example.com/data"));
    
        // 发送GET请求
        QNetworkReply *reply = manager.get(request);
    
        // 连接请求完成的信号
        QObject::connect(reply, &QNetworkReply::finished, [&](){
            // 判断请求是否成功
            if(reply->error() == QNetworkReply::NoError)
            {
                // 读取响应的数据
                QByteArray data = reply->readAll();
                qDebug() << "Response: " << data;
            }
            else
            {
                qDebug() << "Error: " << reply->errorString();
            }
    
            // 请求完成后释放reply对象
            reply->deleteLater();
            // 退出应用程序
            a.quit();
        });
    
        return a.exec();
    }
    

    In the above code, we first created a QNetworkAccessManager object, then created a QNetworkRequest object, and set the requested URL. Next, we use the get() method of QNetworkAccessManager to send a GET request and get a QNetworkReply object. Then, we hook up the finished() signal of QNetworkReply, which is fired when the request is completed. In the slot function of the signal, we judge whether the request is successful, if successful, read the response data and output it, otherwise output an error message. Finally, we release the reply object and exit the application.

  6. QNetworkRequest:

  7. Indicates a network request, you can set the request URL, request method, request header and other information.

  8. Interface Description:

  9. 构造函数:
    QNetworkRequest(url: QUrl = QUrl()):构造一个 QNetworkRequest 实例。
    url:可选参数,指定请求的 URL。
    方法:
    setUrl(url: QUrl):设置请求的 URL。
    
    url:QUrl 对象,表示请求的 URL。
    url() -> QUrl:获取请求的 URL。
    
    返回:QUrl 对象,表示请求的 URL。
    setAttribute(attribute: QNetworkRequest.Attribute, value: Any):设置请求的属性。
    
    attribute:QNetworkRequest.Attribute 枚举,表示要设置的属性类型。
    value:任意类型的值,表示要设置的属性值。
    attribute(attribute: QNetworkRequest.Attribute, defaultValue: Any = None) -> Any:获取请求的属性值。
    
    attribute:QNetworkRequest.Attribute 枚举,表示要获取的属性类型。
    defaultValue:可选参数,当属性不存在时返回的默认值。
    返回:任意类型的值,表示请求的属性值。
    hasAttribute(attribute: QNetworkRequest.Attribute) -> bool:检查请求是否具有特定的属性。
    
    attribute:QNetworkRequest.Attribute 枚举,表示要检查的属性类型。
    返回:True 表示请求具有该属性,False 表示请求不具有该属性。
    setRawHeader(headerName: QByteArray, value: QByteArray):设置原始请求头。
    
    headerName:QByteArray 对象,表示请求头的名称。
    value:QByteArray 对象,表示请求头的值。
    rawHeader(headerName: QByteArray) -> QByteArray:获取原始请求头的值。
    
    headerName:QByteArray 对象,表示请求头的名称。
    返回:QByteArray 对象,表示请求头的值。
    hasRawHeader(headerName: QByteArray) -> bool:检查请求是否具有特定的原始请求头。
    
    headerName:QByteArray 对象,表示请求头的名称。
    返回:True 表示请求具有该请求头,False 表示请求不具有该请求头。
    setHeader(header: QNetworkRequest.KnownHeaders, value: Any):设置请求的已知头。
    
    header:QNetworkRequest.KnownHeaders 枚举,表示已知请求头类型。
    value:任意类型的值,表示请求头的值。
    header(header: QNetworkRequest.KnownHeaders) -> Any:获取请求的已知头的值。
    
    header:QNetworkRequest.KnownHeaders 枚举,表示已知请求头类型。
    返回:任意类型的值,表示请求头的值。
    hasRawHeader(headerName: QByteArray) -> bool:检查请求是否具有特定的已知头。
    
    header:QNetworkRequest.KnownHeaders 枚举,表示已知请求头类型。
    返回:True 表示请求具有该已知头,False 表示请求不具有该已知头。
    setSslConfiguration(config: QSslConfiguration):设置 SSL 配置,用于加密连接。
    
    config:QSslConfiguration 对象,表示 SSL 配置。
    sslConfiguration() -> QSslConfiguration:获取当前的 SSL 配置。
    
    返回:QSslConfiguration 对象,表示当前的 SSL 配置。
    枚举类型 QNetworkRequest.Attribute:
    HttpStatusCodeAttribute:HTTP 状态码的属性,用于获取 HTTP 响应状态码。
    HttpReasonPhraseAttribute:HTTP 响应原因短语的属性,用于获取 HTTP 响应的原因短语。
    RedirectionTargetAttribute:重定向目标的属性,用于获取重定向的目标 URL。
    ConnectionEncryptedAttribute:连接是否通过 SSL 加密的属性。
    CacheLoadControlAttribute:缓存加载控制的属性。
    CacheSaveControlAttribute:缓存保存控制的属性。
    SourceIsFromCacheAttribute:源数据是否来自缓存的属性。
    DoNotBufferUploadDataAttribute:不要缓冲上传数据的属性。
    HttpPipeliningAllowedAttribute:是否允许 HTTP 管道传输的属性。
    枚举类型 QNetworkRequest.KnownHeaders:
    QNetworkRequest.KnownHeaders 是一组已知的 HTTP 请求头类型,包括但不限于以下几种:
    
    ContentTypeHeader:表示请求的内容类型。
    ContentLengthHeader:表示请求的内容长度。
    LocationHeader:表示请求的重定向位置。
    LastModifiedHeader:表示请求的最后修改时间。
    CookieHeader:表示请求的 Cookie。
    UserAgentHeader:表示请求的用户代理信息。
    ServerHeader:表示服务器的响应头。
    ContentDispositionHeader:表示请求的内容描述。
    AcceptHeader:表示请求可接受的内容类型。
    

    Use the code:

  10. from PyQt5.QtCore import QUrl
    from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
    from PyQt5.QtWidgets import QApplication
    import sys
    
    def handle_response(reply: QNetworkReply):
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll()
            print("Response data:", data.data().decode('utf-8'))
        else:
            print("Error occurred:", reply.errorString())
    
        reply.deleteLater()
        QApplication.quit()
    
    def make_request():
        url = QUrl("https://jsonplaceholder.typicode.com/posts/1")
        request = QNetworkRequest(url)
    
        manager = QNetworkAccessManager()
        reply = manager.get(request)
        reply.finished.connect(lambda: handle_response(reply))
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        make_request()
        sys.exit(app.exec_())
    

    In this case, we created a simple application that QNetworkAccessManagersends a GET request to a https://jsonplaceholder.typicode.com/posts/1URL that is a test API using the URL, which returns a response in JSON format.

    First, we import the required modules and define a handle_responsefunction to handle the response. In this function, we check if the network reply has no errors, and if there are no errors, we read the response data and print it to the console. If there is an error, we also print out the error message. Finally, we use deleteLater()the method to delete the network reply object and the to QApplication.quit()exit the application.

    Next, we define a make_requestfunction to send the request. We QUrlcreated the requested URL with and then QNetworkRequestcreated the request object with , setting the URL to the requested URL.

    Then, we create a QNetworkAccessManagerobject, which handles network requests. getA GET request is sent via the method, and the response handle_responseis hooked up to the function to handle when the request completes.

    Finally, in mainthe function, we initialize the application and call make_requestthe function to send the request. Finally, use sys.exit(app.exec_())to start the Qt event loop.

  11. QNetworkReply:

    Represents a network response, including response data, status code, response header and other information. It can be used to obtain and process the data returned by the server.
  12. Interface Description:

  13. 方法:
    isFinished() -> bool:检查网络回复是否已完成。
    
    返回:True 表示网络回复已完成,False 表示网络回复未完成。
    isRunning() -> bool:检查网络回复是否正在运行中。
    
    返回:True 表示网络回复正在运行,False 表示网络回复未运行。
    isReadable() -> bool:检查网络回复是否可读。
    
    返回:True 表示网络回复可读,False 表示网络回复不可读。
    error() -> QNetworkReply.NetworkError:获取网络回复的错误代码。
    
    返回:QNetworkReply.NetworkError 枚举,表示网络回复的错误代码。
    errorString() -> str:获取网络回复的错误信息字符串。
    
    返回:字符串,表示网络回复的错误信息。
    readAll() -> QByteArray:读取网络回复的所有数据。
    
    返回:QByteArray 对象,表示网络回复的所有数据。
    read(size: int) -> QByteArray:读取指定大小的数据。
    
    size:要读取的数据大小。
    返回:QByteArray 对象,表示读取的数据。
    attribute(attribute: QNetworkRequest.Attribute, defaultValue: Any = None) -> Any:获取网络回复的属性值。
    
    attribute:QNetworkRequest.Attribute 枚举,表示要获取的属性类型。
    defaultValue:可选参数,当属性不存在时返回的默认值。
    返回:任意类型的值,表示网络回复的属性值。
    header(header: QNetworkRequest.KnownHeaders) -> Any:获取网络回复的已知头的值。
    
    header:QNetworkRequest.KnownHeaders 枚举,表示已知响应头类型。
    返回:任意类型的值,表示网络回复的已知头的值。
    rawHeader(headerName: QByteArray) -> QByteArray:获取网络回复的原始响应头的值。
    
    headerName:QByteArray 对象,表示响应头的名称。
    返回:QByteArray 对象,表示网络回复的原始响应头的值。
    attribute(attribute: QNetworkRequest.Attribute, defaultValue: Any = None) -> Any:获取网络回复的属性值。
    
    attribute:QNetworkRequest.Attribute 枚举,表示要获取的属性类型。
    defaultValue:可选参数,当属性不存在时返回的默认值。
    返回:任意类型的值,表示网络回复的属性值。
    rawHeaderList() -> List[QByteArray]:获取网络回复的原始响应头列表。
    
    返回:QList[QByteArray] 对象,表示网络回复的原始响应头列表。
    枚举类型 QNetworkReply.NetworkError:
    QNetworkReply.NetworkError 枚举表示网络回复的错误代码,包括但不限于以下几种:
    
    NoError:没有错误。
    ConnectionRefusedError:连接被拒绝。
    RemoteHostClosedError:远程主机关闭了连接。
    HostNotFoundError:未找到主机。
    TimeoutError:连接超时。
    OperationCanceledError:操作被取消。
    SslHandshakeFailedError:SSL 握手失败。
    
  14. use code

  15. from PyQt5.QtCore import QUrl
    from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
    from PyQt5.QtWidgets import QApplication
    import sys
    
    def handle_response(reply: QNetworkReply):
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll()
            print("Response data:", data.data().decode('utf-8'))
        else:
            print("Error occurred:", reply.errorString())
    
        reply.deleteLater()
        QApplication.quit()
    
    def make_request():
        url = QUrl("https://jsonplaceholder.typicode.com/posts/1")
        request = QNetworkRequest(url)
    
        manager = QNetworkAccessManager()
        reply = manager.get(request)
        reply.finished.connect(lambda: handle_response(reply))
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        make_request()
        sys.exit(app.exec_())
    

    In this code example, we create a simple application that QNetworkAccessManagersends a GET request to https://jsonplaceholder.typicode.com/posts/1a test API using the URL, which returns a response in JSON format.

    First, we import the required modules and define a handle_responsefunction to handle the response. In this function, we check if the network reply has no errors, and if there are no errors, we read the response data and print it to the console. If there is an error, we also print out the error message. Finally, we use deleteLater()the method to delete the network reply object and the to QApplication.quit()exit the application.

    Next, we define a make_requestfunction to send the request. We QUrlcreated the requested URL with and then QNetworkRequestcreated the request object with , setting the URL to the requested URL.

    Then, we create a QNetworkAccessManagerobject, which handles network requests. getA GET request is sent via the method, and the response handle_responseis hooked up to the function to handle when the request completes.

    Finally, in mainthe function, we initialize the application and call make_requestthe function to send the request. Finally, use sys.exit(app.exec_())to start the Qt event loop.

  16. QNetworkCookieJar:

  17. Used to manage and process cookies in HTTP requests.

  18. Interface Description:

  19. 方法:
    allCookies() -> List[QNetworkCookie]:获取所有的 cookie。
    
    返回:QList[QNetworkCookie],表示所有的 cookie 列表。
    setCookiesFromUrl(cookies: List[QNetworkCookie], url: QUrl):从给定 URL 设置 cookie。
    
    cookies:QList[QNetworkCookie],要设置的 cookie 列表。
    url:QUrl,cookie 所属的 URL。
    deleteCookie(cookie: QNetworkCookie):删除指定的 cookie。
    
    cookie:QNetworkCookie,要删除的 cookie。
    insertCookie(cookie: QNetworkCookie):插入一个新的 cookie。
    
    cookie:QNetworkCookie,要插入的 cookie。
    updateCookie(cookie: QNetworkCookie):更新一个已存在的 cookie。
    
    cookie:QNetworkCookie,要更新的 cookie。
    clear():清空所有的 cookie。
    
    信号:
    cookieAdded(cookie: QNetworkCookie):当一个新的 cookie 被插入时发出的信号。
    
    cookie:QNetworkCookie,新添加的 cookie。
    cookieChanged(cookie: QNetworkCookie):当一个 cookie 被修改时发出的信号。
    
    cookie:QNetworkCookie,被修改的 cookie。
    cookieRemoved(cookie: QNetworkCookie):当一个 cookie 被删除时发出的信号。
    
    cookie:QNetworkCookie,被删除的 cookie。
  20. Use the code:

  21. from PyQt5.QtCore import QUrl
    from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkCookieJar, QNetworkRequest, QNetworkReply
    from PyQt5.QtWidgets import QApplication
    import sys
    
    class MyCookieJar(QNetworkCookieJar):
        def __init__(self):
            super().__init__()
    
        def cookiesForUrl(self, url):
            # 在这里可以自定义返回指定 URL 的 cookie 列表
            return super().cookiesForUrl(url)
    
        def setCookiesFromUrl(self, cookies, url):
            # 在这里可以自定义设置指定 URL 的 cookie
            super().setCookiesFromUrl(cookies, url)
    
    def handle_response(reply: QNetworkReply):
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll()
            print("Response data:", data.data().decode('utf-8'))
        else:
            print("Error occurred:", reply.errorString())
    
        reply.deleteLater()
        QApplication.quit()
    
    def make_request():
        url = QUrl("https://jsonplaceholder.typicode.com/posts/1")
        request = QNetworkRequest(url)
    
        cookie_jar = MyCookieJar()
        manager = QNetworkAccessManager()
        manager.setCookieJar(cookie_jar)
    
        reply = manager.get(request)
        reply.finished.connect(lambda: handle_response(reply))
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        make_request()
        sys.exit(app.exec_())
    

    In this code example, we first define a QNetworkCookieJarsubclass that inherits from MyCookieJar. In this subclass, we can override cookiesForUrlthe method and setCookiesFromUrlmethod to customize the cookie management logic. In the example, we used the default implementation of the parent class, but you can implement custom logic according to your needs.

    Then, in make_requestthe function, we create an MyCookieJarinstance of to manage cookies. We then create a QNetworkAccessManagerobject and set the custom cookie manager to it to use custom cookie management logic in network requests.

    Next, we send a GET request to the https://jsonplaceholder.typicode.com/posts/1URL, which is a test API, and it returns a response in JSON format. After the request is completed, handle_responsethe response data is processed by the function.

    Finally, in mainthe function, we initialize the application and call make_requestthe function to send the request. Finally, use sys.exit(app.exec_())to start the Qt event loop.

  22. QNetworkConfigurationManager:

  23. Used to manage network configuration, such as network connection status, available network interfaces, etc.

  24. Interface Description:

  25. 方法:
    defaultConfiguration() -> QNetworkConfiguration:获取默认的网络配置。
    
    返回:QNetworkConfiguration 对象,表示默认的网络配置。
    allConfigurations(flags: QNetworkConfiguration.StateFlags = QNetworkConfiguration.Active) -> List[QNetworkConfiguration]:获取满足指定条件的所有网络配置列表。
    
    flags:QNetworkConfiguration.StateFlags 枚举,表示要获取的网络配置的状态标志,默认为 QNetworkConfiguration.Active,表示获取活动的网络配置。
    返回:QList[QNetworkConfiguration] 对象,表示满足条件的网络配置列表。
    isOnline() -> bool:检查设备是否在线(即是否连接到网络)。
    
    返回:True 表示设备在线,False 表示设备离线。
    updateConfigurations():更新可用的网络配置列表。
    
    configurationAdded.connect(slot_function):连接一个槽函数,当新的网络配置被添加时触发。
    
    configurationChanged.connect(slot_function):连接一个槽函数,当网络配置发生更改时触发。
    
    configurationRemoved.connect(slot_function):连接一个槽函数,当网络配置被移除时触发。
    
    onlineStateChanged.connect(slot_function):连接一个槽函数,当设备的在线状态发生改变时触发。
    
    信号:
    configurationAdded(configuration: QNetworkConfiguration):当新的网络配置被添加时发出的信号。
    
    configuration:QNetworkConfiguration 对象,新添加的网络配置。
    configurationChanged(configuration: QNetworkConfiguration):当网络配置发生更改时发出的信号。
    
    configuration:QNetworkConfiguration 对象,发生更改的网络配置。
    configurationRemoved(configuration: QNetworkConfiguration):当网络配置被移除时发出的信号。
    
    configuration:QNetworkConfiguration 对象,被移除的网络配置。
    onlineStateChanged(online: bool):当设备的在线状态发生改变时发出的信号。
    
    online:布尔值,表示设备是否在线。

    Code using:

    from PyQt5.QtCore import QCoreApplication, QUrl
    from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkConfigurationManager, QNetworkRequest, QNetworkReply
    
    def handle_response(reply: QNetworkReply):
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll()
            print("Response data:", data.data().decode('utf-8'))
        else:
            print("Error occurred:", reply.errorString())
    
        reply.deleteLater()
        QCoreApplication.quit()
    
    if __name__ == "__main__":
        app = QCoreApplication([])
    
        # Create QNetworkConfigurationManager instance
        config_manager = QNetworkConfigurationManager()
    
        # Check if the device is online
        online = config_manager.isOnline()
        print("Is online:", online)
    
        # Get all active configurations
        configurations = config_manager.allConfigurations()
        for config in configurations:
            print("Configuration Name:", config.name())
            print("Bearer Type:", config.bearerTypeName())
    
        # Create QNetworkAccessManager instance
        manager = QNetworkAccessManager()
    
        # Make a GET request
        url = QUrl("https://jsonplaceholder.typicode.com/posts/1")
        request = QNetworkRequest(url)
        reply = manager.get(request)
        reply.finished.connect(lambda: handle_response(reply))
    
        app.exec_()
    

    In this code example, we first import the required modules and create an QCoreApplicationinstance to run the Qt event loop.

    Then, we create an QNetworkConfigurationManagerinstance config_managerand use isOnline()the method to check if the device is online and print out the online status.

    Next, we use allConfigurations()the method to get a list of all network configurations, and traverse and print the name and connection type of each configuration.

    Then, we create an QNetworkAccessManagerinstance managerof which is used to send network requests. In this example, we're sending a GET request to https://jsonplaceholder.typicode.com/posts/1the URL, which is a test API, which returns a response in JSON format.

    Finally, we connect reply.finishedthe signal to handle_responsethe function, which handles the response data.

  26. QTcpSocket and QUdpSocket:

  27. It is used to create TCP and UDP sockets to realize network communication based on TCP and UDP.

  28. Interface Description:

  29. QTcpSocket:
  30. method:

  31. connectToHost(host: str, port: int):连接到指定的主机和端口。
    disconnectFromHost():断开与主机的连接。
    write(data: bytes):将数据写入连接。
    readAll() -> bytes:读取所有可用数据。
    waitForReadyRead(msecs: int):等待数据准备就绪,最多等待指定毫秒数。
    state() -> QAbstractSocket.SocketState:获取当前 socket 状态。
    
  32. Signal:

  33. connected:当连接成功建立时发出。
    disconnected:当连接关闭时发出。
    readyRead:当有数据可读取时发出。
    QUdpSocket
  34. QUdpSocket is a class for network communication based on UDP protocol. It is suitable for data transfer without the need to establish a persistent connection. Here are some commonly used methods and signals:

    method:

    bind(port: int, mode: QAbstractSocket.BindFlag = QAbstractSocket.DefaultForPlatform):绑定到指定的端口和模式。
    writeDatagram(data: bytes, host: str, port: int):将数据报文发送到指定的主机和端口。
    readDatagram(maxSize: int) -> Tuple[bytes, str, int]:读取一个数据报文和发送者的信息。


    Signal:

  35. readyRead:当有数据可读取时发出。
    这些类都提供了一系列用于管理网络通信的方法和信号。你可以根据自己的需求,选择适当的类和方法来实现 TCP 或 UDP 的数据传输。在实际使用时,你需要创建这些类的对象,并根据需要连接信号和调用方法来进行网络通信操作。

  36. Use the code:

  37. Client code for TCP communication using QTcpSocket:
  38. from PyQt5.QtCore import QCoreApplication
    from PyQt5.QtNetwork import QTcpSocket
    
    def handle_connected():
        print("Connected to server.")
        tcp_socket.write(b"Hello, server!")
    
    def handle_ready_read():
        data = tcp_socket.readAll()
        print("Received data from server:", data.data().decode())
    
    def handle_disconnected():
        print("Disconnected from server.")
        QCoreApplication.quit()
    
    if __name__ == "__main__":
        app = QCoreApplication([])
    
        tcp_socket = QTcpSocket()
        tcp_socket.connected.connect(handle_connected)
        tcp_socket.readyRead.connect(handle_ready_read)
        tcp_socket.disconnected.connect(handle_disconnected)
    
        tcp_socket.connectToHost("127.0.0.1", 12345)
    
        app.exec_()
    
    Server-side code for TCP communication using QTcpSocket:
  39. from PyQt5.QtCore import QCoreApplication
    from PyQt5.QtNetwork import QTcpServer
    
    def handle_new_connection():
        client_socket = tcp_server.nextPendingConnection()
        client_socket.readyRead.connect(handle_ready_read)
        client_socket.disconnected.connect(client_socket.deleteLater)
    
    def handle_ready_read():
        client_socket = sender()
        data = client_socket.readAll()
        print("Received data from client:", data.data().decode())
        client_socket.write(b"Hello, client!")
        client_socket.disconnectFromHost()
    
    if __name__ == "__main__":
        app = QCoreApplication([])
    
        tcp_server = QTcpServer()
        tcp_server.newConnection.connect(handle_new_connection)
    
        tcp_server.listen(port=12345)
    
        app.exec_()
    
    Code for UDP communication using QUdpSocket:
  40. from PyQt5.QtCore import QCoreApplication
    from PyQt5.QtNetwork import QUdpSocket
    
    def handle_ready_read():
        while udp_socket.hasPendingDatagrams():
            data, host, port = udp_socket.readDatagram(1024)
            print(f"Received data from {host.toString()}:{port}: {data.data().decode()}")
    
    if __name__ == "__main__":
        app = QCoreApplication([])
    
        udp_socket = QUdpSocket()
        udp_socket.readyRead.connect(handle_ready_read)
    
        udp_socket.bind(12345)
    
        app.exec_()
    
  41. QSslSocket and QSslConfiguration:

  42. It is used to support encrypted SSL/TLS communication to realize secure network communication.

  43. Interface Description:

  44. QSslSocket
  45. method:
  46. setSslConfiguration(config: QSslConfiguration):设置用于 SSL 连接的配置。
    sslConfiguration() -> QSslConfiguration:获取当前 SSL 配置。
    connectToHostEncrypted(host: str, port: int, mode: QIODevice.OpenMode = QIODevice.ReadWrite):使用 SSL 加密连接到指定主机和端口。
    
    Signal:
  47. encrypted:当 SSL 加密连接成功建立时发出。
    sslErrors:当 SSL 错误发生时发出。
    QSslConfiguration
  48. QSslConfiguration is a class used to configure SSL connections. It contains various settings of SSL, such as encryption algorithm, certificate verification, protocol version, etc. Here are some commonly used methods:

    method:
    setDefaultConfiguration(config: QSslConfiguration):设置默认的 SSL 配置。
    defaultConfiguration() -> QSslConfiguration:获取默认的 SSL 配置。
    setPeerVerifyMode(verifyMode: QSslSocket.PeerVerifyMode):设置对端证书验证模式。
    peerVerifyMode() -> QSslSocket.PeerVerifyMode:获取对端证书验证模式。
    setProtocol(sslProtocol: QSsl.SslProtocol):设置 SSL 协议版本。
    protocol() -> QSsl.SslProtocol:获取 SSL 协议版本。

    QSslConfiguration also has some other methods for setting and getting certificate, private key, CA (Certificate Authority) and password related information.

    Note that when using QSslSocket and QSslConfiguration for encrypted communication, you need to install a library that supports SSL, such as OpenSSL or Secure Transport (on macOS). Qt provides the supportsSsl() static method of QSslSocket to check whether the current Qt library supports SSL.

  49. QHostInfo:

  50. Used to get the IP address and hostname of a host.

  51. Interface Description:

  52. method:
  53. lookupHost(hostName: str, receiver: QObject, member: Callable):异步查询主机名对应的 IP 地址信息,将结果通过指定的信号接收。receiver 是接收信号的对象,member 是信号处理函数。
    abortHostLookup(receiver: QObject):中断正在进行的主机名查询。
    localHostName() -> str:获取本地主机名。
    localDomainName() -> str:获取本地域名。
    Signal:
  54. finished(QHostInfo):主机名查询完成后发出的信号。QHostInfo 包含了查询到的 IP 地址列表和主机名列表。

    Use the code:

  55. from PyQt5.QtCore import QCoreApplication
    from PyQt5.QtNetwork import QHostInfo
    
    def handle_host_lookup(info: QHostInfo):
        if info.error() == QHostInfo.NoError:
            print("Host name:", info.hostName())
            print("IP addresses:")
            for address in info.addresses():
                print("  -", address.toString())
        else:
            print("Error occurred:", info.errorString())
    
        QCoreApplication.quit()
    
    if __name__ == "__main__":
        app = QCoreApplication([])
    
        host_name = "www.google.com"
        QHostInfo.lookupHost(host_name, app, handle_host_lookup)
    
        app.exec_()
    

  56. QTcpServer:

  57. It is used to create a TCP server to realize server-side network communication.

  58. Interface Description:

  59. method:
  60. listen(host: QHostAddress = QHostAddress.Any, port: int = 0) -> bool:开始在指定主机和端口上监听连接请求。
    close():停止监听连接请求,并关闭服务器。
    isListening() -> bool:检查服务器是否正在监听连接请求。
    serverAddress() -> QHostAddress:获取服务器的地址。
    serverPort() -> int:获取服务器的端口。
    Signal:
  61. newConnection:当有新的连接请求到达时发出。

    Use the code:

  62. from PyQt5.QtCore import QCoreApplication
    from PyQt5.QtNetwork import QTcpServer, QTcpSocket
    
    class MyTcpServer(QTcpServer):
        def incomingConnection(self, socketDescriptor):
            print("New connection established.")
            client_socket = QTcpSocket()
            client_socket.setSocketDescriptor(socketDescriptor)
            client_socket.readyRead.connect(self.handle_ready_read)
            client_socket.disconnected.connect(client_socket.deleteLater)
    
        def handle_ready_read(self):
            client_socket = self.sender()
            data = client_socket.readAll()
            print("Received data from client:", data.data().decode())
            client_socket.write(b"Hello, client!")
            client_socket.disconnectFromHost()
    
    if __name__ == "__main__":
        app = QCoreApplication([])
    
        server = MyTcpServer()
        server.listen(port=12345)
    
        app.exec_()
    
  63. QAbstractSocket:

  64. It is the base class of QTcpSocket and QUdpSocket, providing some common functions, such as connection establishment and disconnection, error handling, etc.

  65. Interface Description:

  66. method:
  67. bind(address: QHostAddress, port: int, mode: BindMode = DefaultForPlatform) -> bool:绑定到指定的地址和端口,用于服务器端的绑定操作。
    connectToHost(hostName: str, port: int, openMode: QIODevice.OpenMode = ReadWrite):连接到指定的主机和端口,用于客户端的连接操作。
    disconnectFromHost():断开与主机的连接。
    abort():中止当前操作并立即关闭套接字。
    state() -> QAbstractSocket.SocketState:获取当前套接字的状态,返回值为 SocketState 枚举类型。
    error() -> QAbstractSocket.SocketError:获取套接字的错误状态,返回值为 SocketError 枚举类型。
    errorString() -> str:获取描述错误状态的字符串。
    isValid() -> bool:检查套接字是否有效。
    setSocketOption(option: QAbstractSocket.SocketOption, value: Any) -> bool:设置套接字选项。
    socketOption(option: QAbstractSocket.SocketOption) -> Any:获取套接字选项的值。
    Signal:
  68. connected:当连接成功建立时发出。
    disconnected:当连接断开时发出。
    hostFound:当主机名解析成功时发出。
    stateChanged(QAbstractSocket.SocketState):当套接字状态发生变化时发出。
    errorOccurred(QAbstractSocket.SocketError):当发生错误时发出。
    Enumerated type:
  69. QAbstractSocket.SocketState:描述套接字状态的枚举类型,包括 UnconnectedState、HostLookupState、ConnectingState、ConnectedState、BoundState 和 ClosingState。
    QAbstractSocket.SocketError:描述套接字错误的枚举类型,包括 ConnectionRefusedError、RemoteHostClosedError、HostNotFoundError、SocketAccessError 等等。

    The above are some main components and functions of Qt network communication. You can choose appropriate components and methods to develop network communication according to specific needs.

Guess you like

Origin blog.csdn.net/qq_36541069/article/details/132063526