[100 days proficient in python] Day40: GUI interface programming_PyQt from entry to actual combat (end)_network programming and packaging release

Table of contents

 8 Network programming

8.1 Network communication using the PyQt network module

Server-side example

client example

 8.2 Handling network requests and responses

9 Packaging and publishing

9.1 Create an executable or installer

9.2 Solving dependency problems

9.3 Publishing PyQt applications to different platforms

9.3.1 Publishing to Windows

9.3.2 Publishing to macOS

9.3.3 Publishing to Linux

9.4 Cross-platform considerations


 8 Network programming

        Network programming is a key part of enabling communication between different computers. In PyQt, you can use Qt's network module to implement network communication, including creating client and server applications, and handling network requests and responses. The following detailed explanations and examples demonstrate how to do network programming in PyQt.

8.1 Network communication using the PyQt network module

        Qt's network module provides many classes to implement different types of network communication, including TCP and UDP based communication. In this example, we'll focus on TCP-based communication.

Server side example:

        The following is a simple server-side example showing how to use PyQt's network module to create a TCP-based server application:

import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtNetwork import QTcpServer, QTcpSocket, QHostAddress

class Server(QTcpServer):
    def __init__(self):
        super().__init__()
        self.listen(QHostAddress.SpecialAddress.AnyIPv4, 12345)  # 使用正确的地址类型
        self.newConnection.connect(self.on_new_connection)

    def on_new_connection(self):
        client_socket = self.nextPendingConnection()  # 获取新连接的客户端套接字
        client_socket.readyRead.connect(self.on_ready_read)  # 连接readyRead信号到处理函数

    def on_ready_read(self):
        client_socket = self.sender()  # 获取发送信号的客户端套接字
        data = client_socket.readAll()  # 读取客户端发送的数据
        print("Received:", data.decode())  # 打印接收到的数据

        response = "Server response: " + data.decode()
        client_socket.write(response.encode())  # 发送响应给客户端

app = QApplication(sys.argv)
server = Server()
sys.exit(app.exec())

Client example:

The following is a simple client example showing how to use PyQt's network module to create a TCP-based client application:

import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtNetwork import QTcpSocket

class ClientApp(QApplication):
    def __init__(self, argv):
        super().__init__(argv)
        self.client = Client()
        self.client.connectToHost("127.0.0.1", 12345)  # 连接到服务器

class Client(QTcpSocket):
    def __init__(self):
        super().__init__()
        self.connected.connect(self.on_connected)  # 连接到服务器后触发的槽函数
        self.readyRead.connect(self.on_ready_read)  # 当有数据可读时触发的槽函数
        self.disconnected.connect(self.on_disconnected)  # 当与服务器断开连接时触发的槽函数

    def on_connected(self):
        print("Connected to server")  # 连接成功后打印消息
        message = "Hello, server!"
        self.write(message.encode('utf-8'))  # 发送消息给服务器

    def on_ready_read(self):
        data = self.readAll()  # 读取服务器发来的数据
        print(f"Received from server: {data.decode('utf-8')}")  # 打印接收到的数据

    def on_disconnected(self):
        print("Disconnected from server")  # 断开连接时打印消息

if __name__ == "__main__":
    app = ClientApp(sys.argv)  # 创建应用程序对象
    sys.exit(app.exec())  # 运行应用程序事件循环

 8.2 Handling network requests and responses:

          The above code is an example of using the PyQt6 library to implement TCP-based network communication. It involves a simple client and server and demonstrates the basic interaction of sending requests and responses between the two.

Server side code :

  1. Import the required modules.
  2. Create a class that inherits from QTcpServer, Serveroverriding its constructor.
  3. In the constructor, use listenthe method to listen on a specific port on the local host (12345 in this case).
  4. Use newConnectiona signal to connect to the newly connected slot function on_new_connection.
  5. In on_new_connection, get a new client socket, and connect readyReadthe signal to the handler function on_ready_read.
  6. In on_ready_read, read the request sent by the client and print it.
  7. Generate a response message, encode it and send it to the client.

Client code :

  1. Import the required modules.
  2. Create a class that inherits from QApplication, ClientAppoverriding its constructor.
  3. In the constructor, create a Clientobject and connect to the server host and port.
  4. In Clientthe class, inherited from QTcpSocket, override its constructor.
  5. In the constructor, connect connectedsignal to on_connectedslot, connect readyReadsignal to on_ready_readslot, connect disconnectedsignal to on_disconnectedslot.
  6. In on_connected, send a request message to the server.
  7. In on_ready_read, read the response data from the server and print it.
  8. In on_disconnected, print a disconnected message from the server.

Summarize:

  • This example shows simple network communication based on PyQt6.
  • The server listens on a port on the local host and handles client connections, requests and responses.
  • A client connects to a server, sends a request, and waits for a response from the server.
  • Comments in the code explain the function and steps of each part.
  • This is just a basic example and doesn't take into account error handling, security, protocols, etc.
  • In practical applications, you can extend the functions as needed to meet specific needs.

9 Packaging and publishing

        Packaging and publishing are important steps in delivering your PyQt application to users. In this section, I'll explain in detail how to create executables or installers, resolve dependencies, and publish PyQt applications to different platforms.

9.1 Create an executable or installer

Use PyInstaller:

PyInstaller is a commonly used packaging tool that can package your Python code and dependent libraries into a stand-alone executable file.

The following is an example of packaging a PyQt application into an executable using PyInstaller:

  1. First, install PyInstaller:

pip install pyinstaller

Then, execute the following command on the command line:

pyinstaller --onefile your_app.py

This will distgenerate an executable in the folder that you can distribute to users.

9.2 Solving dependency problems

When you package a PyQt application, you need to make sure to include all dependent libraries so that the application can run properly in different environments. PyInstaller automatically detects PyQt dependencies, but for other Python libraries, you may need to specify them manually.

Before packaging, you can create a requirements.txtfile listing all the dependencies your application needs. Then use the following command when packaging:

pyinstaller --onefile --requirements=requirements.txt your_app.py

9.3 Publishing PyQt applications to different platforms

        PyQt supports running on different platforms, including Windows, macOS and Linux. Before publishing, you need to make sure to test that your application works correctly on the target platform. Publishing PyQt applications to different platforms involves some platform-specific considerations and steps. The following is a general guideline for distributing PyQt applications to different operating systems (Windows, macOS and Linux):

 9.3.1 Publishing to Windows

  1. Packaging the executable: Use PyInstaller or a similar tool to package your PyQt application into a standalone executable. Be sure to test this executable on Windows to make sure it works correctly on different Windows versions.

  2. Create an installer: You can use tools such as Inno Setup, NSIS (Nullsoft Scriptable Install System) to create an installer for installing your application. This allows users to easily install your app and add it to their start menu.

9.3.2 Publishing to macOS

  1. Packaging as an .app file: Use the PyInstaller or py2app tools to package your PyQt application into an .app file, which is the standard format for macOS applications.

  2. Configure Icon and Metadata: Add the appropriate icon and metadata for your application, which will be displayed in the application launcher and in the Dock.

  3. Code Signing: Obtaining an Apple Developer Certificate and code signing your app is usually required before publishing to macOS. This increases application security and user trust.

9.3.3 Publishing to Linux

  1. Package executable: Use PyInstaller, cx_Freeze or similar tools to package your PyQt application into an executable. On Linux, applications are usually placed in the /usr/binor /usr/local/bindirectory.

  2. Create a launcher shortcut: Depending on the Linux distribution, you may need to create a launcher shortcut so that users can easily launch your application. These shortcuts are usually added to the application menu.

9.4 Cross-platform considerations

  1. Testing: Be sure to test thoroughly on the target operating system before releasing it to ensure that the application works correctly on different platforms.

  2. Dependency Management: Ensures that all dependent libraries required by the application are included at release time. Using virtual environments can help isolate dependencies on different platforms.

  3. Documentation and Support: Provide proper documentation and support for users to install and use your application on different platforms.

  4. Version Control: Consider using a version control system so that application versions on different platforms can be easily tracked and managed.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/132366288