Python和PySide6实现分别实现tcp通信。

通用界面代码:ui.py

python 复制代码
#tcp通讯/ui.py
from PySide6.QtWidgets import *

class Window(QWidget):

    def __init__(self):
        super().__init__()
        self.init_ui()
    def init_ui(self):
        self.plainTextEdit = QPlainTextEdit(self)
        self.plainTextEdit.setGeometry(20,20,200,200)

    def add_str(self,meg:str):
        self.plainTextEdit.appendHtml(f"<p>{meg}</p>")
        scrollbar = self.plainTextEdit.verticalScrollBar()
        if scrollbar.isVisible():
            scrollbar.setSliderPosition(scrollbar.maximum())

Python实现TCP 服务端代码:

python 复制代码
import socket
import sys
import threading
from PySide6.QtWidgets import *
from ui import Window


class TCP_Server_Python:
    def __init__(self):
        self.ui = Window()
        self.ui.show()
        self.socket_thread = threading.Thread(target=self.do_job, daemon=True)
        self.socket_thread.start()
    def do_job(self):
        with socket.socket() as server:
            server.bind(('0.0.0.0',6002))
            server.listen(10)
            print("服务器已经启动。。。。。。。")
            conn, _server = server.accept()
            while True:
                print("已经连接")
                data = b''
                try:
                    data = conn.recv(1024)
                except Exception as e:
                    pass
                else:
                    if data == b'\x01':
                        print("关闭")
                        break
                    self.ui.add_str(data)





if __name__ == '__main__':

    # 创建一个应用程序实例
    app = QApplication(sys.argv)

    # 创建一个顶层窗口
    window = TCP_Server_Python()


    # 进入应用程序的主循环,等待事件处理
    sys.exit(app.exec())

Pyside6中QTcpSocket实现代码:

python 复制代码
import sys
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from ui import Window
from PySide6.QtNetwork import QTcpServer,QHostAddress,QTcpSocket

class Qt_Tcp_Server:
    def __init__(self):
        self.ui = Window()
        self.ui.show()

        self.tcp_servet = QTcpServer()
        self.tcp_servet.listen(QHostAddress.SpecialAddress.Any,port=6002)
        self.ui.add_str("...服务器已经启动")
        self.tcp_servet.newConnection.connect(self.on_new_connection)#连接信号

    @Slot()
    def on_new_connection(self):
        '''新的连接槽函数'''
        second_socket:QTcpSocket = self.tcp_servet.nextPendingConnection()
        client_ip = second_socket.peerAddress().toString().split(":")[-1]
        client_port = second_socket.peerPort()
        msg = f"新连接的客户端ip地址为:{client_ip},端口号:{client_port}"
        self.ui.add_str(msg)
        second_socket.readyRead.connect(lambda :self.on_second_socket_ready_read(second_socket))
    @Slot()
    def on_second_socket_ready_read(self,socket:QTcpSocket):
        '''当有数据时触发该函数'''
        # data = socket.readAll() #全部读取
        #读取一行
        while socket.bytesAvailable()>0:
            line_byte = socket.readLine()
            self.ui.add_str(line_byte)


if __name__ == '__main__':

    app = QApplication(sys.argv)

    window = Qt_Tcp_Server()

    sys.exit(app.exec())
相关推荐
带土19 分钟前
1. Qt-的安装和环境变量的配置
开发语言·qt
夫唯不争,故无尤也34 分钟前
梯度累计原理:数学可行性与PyTorch实现
人工智能·pytorch·python
我的xiaodoujiao39 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 27--二次封装方法--优化断言结果
python·学习·测试工具·pytest
q***d1731 小时前
Rust并发模型
开发语言·后端·rust
love530love1 小时前
解决 ComfyUI 启动显示 ‘sox‘ 命令未找到错误:从安装到配置的完整指南
人工智能·windows·python·aigc·comfyui·comfyui-manager
CircleMouse1 小时前
介绍几个axios接口请求顺序的问题
开发语言·前端·javascript·ecmascript
baivfhpwxf20231 小时前
用TCP服务端向多个客户端分发图片,客户端接收并处理图片,再将处理结果返回给服务端
服务器·开发语言·网络·tcp/ip·c#
资深web全栈开发1 小时前
Golang Cobra 教程:构建强大的CLI应用
开发语言·后端·golang
J***79391 小时前
Python在机器学习中的数据处理
开发语言·python·机器学习