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())
相关推荐
码路飞2 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽4 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程8 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪8 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook9 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python