Pyside2和socket实现一个服务器与多个客户端通信的python代码
时间: 2023-04-06 18:05:15 浏览: 146
我可以回答这个问题。以下是一个使用Pyside2和socket实现一个服务器与多个客户端通信的Python代码的示例:
```python
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import socket
import threading
class Server(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Server')
self.setGeometry(100, 100, 400, 300)
self.textbox = QTextEdit(self)
self.textbox.setReadOnly(True)
self.textbox.setGeometry(10, 10, 380, 200)
self.start_button = QPushButton('Start', self)
self.start_button.setGeometry(10, 220, 80, 30)
self.start_button.clicked.connect(self.start_server)
self.stop_button = QPushButton('Stop', self)
self.stop_button.setGeometry(100, 220, 80, 30)
self.stop_button.clicked.connect(self.stop_server)
self.show()
def start_server(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind(('localhost', 12345))
self.server_socket.listen(5)
self.textbox.append('Server started.')
self.clients = []
self.running = True
self.accept_thread = threading.Thread(target=self.accept_clients)
self.accept_thread.start()
def stop_server(self):
self.running = False
self.server_socket.close()
self.textbox.append('Server stopped.')
def accept_clients(self):
while self.running:
client_socket, address = self.server_socket.accept()
self.clients.append(client_socket)
self.textbox.append('Client connected: ' + str(address))
client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))
client_thread.start()
def handle_client(self, client_socket):
while self.running:
try:
data = client_socket.recv(1024)
if data:
self.textbox.append('Received from client: ' + data.decode())
for client in self.clients:
if client != client_socket:
client.send(data)
else:
self.clients.remove(client_socket)
self.textbox.append('Client disconnected.')
break
except:
self.clients.remove(client_socket)
self.textbox.append('Client disconnected.')
break
if __name__ == '__main__':
app = QApplication(sys.argv)
server = Server()
sys.exit(app.exec_())
```
这个代码实现了一个基于Pyside2和socket的服务器,可以与多个客户端进行通信。当客户端连接到服务器时,服务器会将其加入客户端列表,并启动一个新的线程来处理该客户端的消息。当客户端发送消息时,服务器会将该消息广播给所有客户端。当客户端断开连接时,服务器会将其从客户端列表中移除。
阅读全文