python socket通信并相互输出在gui窗口上
时间: 2023-08-11 19:20:49 浏览: 143
GUI界面与Socket之间的交互
好的,这里提供一个使用PyQt5实现socket通信并显示在GUI窗口上的示例代码。
服务端代码:
```python
import socket
import threading
HOST = 'localhost'
PORT = 8888
class ServerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((HOST, PORT))
self.server_socket.listen(1)
print('Waiting for client connection...')
def run(self):
while True:
conn, addr = self.server_socket.accept()
print('Connected by', addr)
client_thread = ClientThread(conn, addr)
client_thread.start()
class ClientThread(threading.Thread):
def __init__(self, conn, addr):
threading.Thread.__init__(self)
self.conn = conn
self.addr = addr
def run(self):
while True:
data = self.conn.recv(1024)
if not data:
break
print('Received:', data.decode())
self.conn.sendall(data)
self.conn.close()
print('Connection closed by', self.addr)
server_thread = ServerThread()
server_thread.start()
```
客户端代码:
```python
import sys
import socket
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QLineEdit, QVBoxLayout
HOST = 'localhost'
PORT = 8888
class ClientWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.connectServer()
def initUI(self):
self.setWindowTitle('Socket Communication')
self.setGeometry(100, 100, 400, 300)
self.text_edit = QTextEdit()
self.text_edit.setReadOnly(True)
self.text_edit.setFocusPolicy(Qt.NoFocus)
self.line_edit = QLineEdit()
self.line_edit.returnPressed.connect(self.sendMsg)
layout = QVBoxLayout()
layout.addWidget(self.text_edit)
layout.addWidget(self.line_edit)
self.setLayout(layout)
def connectServer(self):
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_socket.connect((HOST, PORT))
self.recvThread = RecvThread(self.client_socket)
self.recvThread.recvSignal.connect(self.recvMsg)
self.recvThread.start()
def sendMsg(self):
msg = self.line_edit.text().strip()
if msg:
self.client_socket.sendall(msg.encode())
self.text_edit.append('Client: ' + msg)
self.line_edit.clear()
def recvMsg(self, msg):
self.text_edit.append('Server: ' + msg.decode())
class RecvThread(threading.Thread):
recvSignal = pyqtSignal(bytes)
def __init__(self, conn):
threading.Thread.__init__(self)
self.conn = conn
def run(self):
while True:
data = self.conn.recv(1024)
if not data:
break
self.recvSignal.emit(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = ClientWidget()
widget.show()
sys.exit(app.exec_())
```
运行服务端代码,然后运行客户端代码,即可在GUI窗口中输入消息并看到服务器的响应。注意,这里使用了PyQt5的信号槽机制来在接收线程中将消息传递给主线程进行显示。
阅读全文