pyside6 socket通信例程
时间: 2024-05-02 22:15:04 浏览: 197
Pyside6是一个用于创建跨平台桌面应用程序的Python库,它提供了丰富的GUI组件和功能。在Pyside6中,可以使用socket模块进行网络通信。下面是一个简单的Pyside6 socket通信例程:
```python
import sys
from PySide6.QtCore import Qt, QThread, Signal
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QTextEdit, QPushButton
import socket
class ServerThread(QThread):
message_received = Signal(str)
def __init__(self):
super().__init__()
def run(self):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8888))
server_socket.listen(1)
while True:
client_socket, address = server_socket.accept()
message = client_socket.recv(1024).decode()
self.message_received.emit(message)
client_socket.close()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Socket通信例程")
self.setGeometry(100, 100, 400, 300)
layout = QVBoxLayout()
self.text_edit = QTextEdit()
layout.addWidget(self.text_edit)
self.button = QPushButton("启动服务器")
self.button.clicked.connect(self.start_server)
layout.addWidget(self.button)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def start_server(self):
self.button.setEnabled(False)
self.server_thread = ServerThread()
self.server_thread.message_received.connect(self.display_message)
self.server_thread.start()
def display_message(self, message):
self.text_edit.append(message)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
```
上述例程实现了一个简单的Pyside6窗口应用程序,其中包含一个文本编辑框和一个按钮。点击按钮后,程序会启动一个服务器线程,监听本地8888端口的连接。当有客户端连接并发送消息时,服务器线程会将消息显示在文本编辑框中。
阅读全文