I am trying to create a server and client to send and receive messages. My problem is to send and receive between the client and the server.
client.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_())
server.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_())
I have searched but I am so confused. I found some code, but I can't understand what it does exactly:
data = input()
block = QByteArray()
out = QDataStream(block, QIODevice.ReadWrite)
out.writeQString(data)
clientConnection = self.tcpServer.nextPendingConnection()
clientConnection.write(block)
clientConnection.disconnectFromHost()
client.py
server.py
It comes with very limited error handling but shows you the basics.
Edited to explain the code you wanted explaining