我正在尝试创建一个服务器和客户端来发送和接收消息。我的问题是在客户端和服务器之间发送和接收。
客户端.py:
from PyQt5.QtCore import QIODevice
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtNetwork import QTcpSocket
class Client(QDialog):
def __init__(self):
super().__init__()
HOST = '127.0.0.1'
PORT = 8000
self.tcpSocket = QTcpSocket(self)
self.tcpSocket.connectToHost(HOST, PORT, QIODevice.ReadWrite)
self.tcpSocket.readyRead.connect(self.dealCommunication)
self.tcpSocket.error.connect(self.displayError)
def dealCommunication(self):
print("connected !\n")
# i want here to send and receive messages
def displayError(self):
print(self, "The following error occurred: %s." % self.tcpSocket.errorString())
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
client = Client()
sys.exit(client.exec_())
服务器.py:
import sys
from PyQt5.QtCore import QByteArray, QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtNetwork import QHostAddress, QTcpServer, QTcpSocket
class Server(QDialog, QTcpSocket):
def __init__(self):
super().__init__()
self.tcpServer = None
def sessionOpened(self):
self.tcpServer = QTcpServer(self)
PORT = 8000
address = QHostAddress('127.0.0.1')
self.tcpServer.listen(address, PORT)
self.tcpServer.newConnection.connect(self.dealCommunication)
def dealCommunication(self):
# i want here to send and receive messages
data = input()
block = QByteArray()
out = QDataStream(block, QIODevice.ReadWrite)
out.writeQString(data)
clientConnection = self.tcpServer.nextPendingConnection()
clientConnection.write(block)
clientConnection.disconnectFromHost()
if __name__ == '__main__':
app = QApplication(sys.argv)
server = Server()
server.sessionOpened()
sys.exit(server.exec_())
我已经搜索过,但我很困惑。我找到了一些代码,但我不明白它到底做了什么:
data = input()
block = QByteArray()
out = QDataStream(block, QIODevice.ReadWrite)
out.writeQString(data)
clientConnection = self.tcpServer.nextPendingConnection()
clientConnection.write(block)
clientConnection.disconnectFromHost()