欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > Python和PySide6实现分别实现tcp通信。

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

2024/10/24 11:15:07 来源:https://blog.csdn.net/weixin_49577420/article/details/141685519  浏览:    关键词:Python和PySide6实现分别实现tcp通信。

通用界面代码:ui.py


#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 服务端代码:

import socket
import sys
import threading
from PySide6.QtWidgets import *
from ui import Windowclass 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:passelse:if data == b'\x01':print("关闭")breakself.ui.add_str(data)if __name__ == '__main__':# 创建一个应用程序实例app = QApplication(sys.argv)# 创建一个顶层窗口window = TCP_Server_Python()# 进入应用程序的主循环,等待事件处理sys.exit(app.exec())

Pyside6中QTcpSocket实现代码:

import sys
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from ui import Window
from PySide6.QtNetwork import QTcpServer,QHostAddress,QTcpSocketclass 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())

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com