Отправка сообщения по нажатию кнопки PyQt5
я новичок, подскажите как мне переделать код сервера, что бы он отправлял сообщение клиенту по нажатию на кнопки. Код сервера:
import sys
from PyQt5.QtCore import QByteArray, QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton
from PyQt5.QtNetwork import QHostAddress, QTcpServer
class Server(QDialog):
def __init__(self):
super().__init__()
self.tcpServer = None
self.button = QPushButton("Click", self)
self.button.move(50, 50)
def sessionOpened(self):
self.tcpServer = QTcpServer(self)
PORT = 8000
address = QHostAddress('127.0.0.1')
if not self.tcpServer.listen(address, PORT):
print("cant listen!")
self.close()
return
self.tcpServer.newConnection.connect(self.dealCommunication)
def dealCommunication(self):
clientConnection = self.tcpServer.nextPendingConnection()
block = QByteArray()
out = QDataStream(block, QIODevice.WriteOnly)
out.writeUInt16(0)
message = "sdfsdfsdf4terg3grgjggy"
message = bytes(message, encoding='ascii')
out.writeString(message)
out.device().seek(0)
out.writeUInt16(block.size() - 2)
clientConnection.disconnected.connect(clientConnection.deleteLater)
clientConnection.write(block)
clientConnection.disconnectFromHost()
if __name__ == '__main__':
app = QApplication(sys.argv)
server = Server()
server.button.clicked.connect(server.sessionOpened)
sys.exit(server.exec_())
Код клиента:
from PyQt5.QtCore import QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket
class Client(QDialog):
def __init__(self):
super().__init__()
self.tcpSocket = QTcpSocket(self)
self.blockSize = 0
self.makeRequest()
self.tcpSocket.waitForConnected(1000)
self.tcpSocket.readyRead.connect(self.dealCommunication)
self.tcpSocket.error.connect(self.displayError)
def makeRequest(self):
HOST = '127.0.0.1'
PORT = 8000
self.tcpSocket.connectToHost(HOST, PORT)
def dealCommunication(self):
instr = QDataStream(self.tcpSocket)
#instr.setVersion(QDataStream.Qt_5_0)
if self.blockSize == 0:
if self.tcpSocket.bytesAvailable() < 2:
return
self.blockSize = instr.readUInt16()
if self.tcpSocket.bytesAvailable() < self.blockSize:
return
print(str(instr.readString(), encoding='ascii'))
def displayError(self, socketError):
if socketError == QAbstractSocket.RemoteHostClosedError:
pass
else:
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_())
Ответы (1 шт):
Автор решения: Sergey Tatarincev
→ Ссылка
Вы зачем-то закрываете соединение сразу после его установления. Вам же надо при установлении соединения запомнить это соединение (QTcpSocket) а по нажатию кнопки просто отправлять текст (см. слот для кнопки sendText)
import sys
from PyQt5.QtCore import QByteArray, QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QInputDialog
from PyQt5.QtNetwork import QHostAddress, QTcpServer
class Server(QDialog):
def __init__(self):
super().__init__()
self.tcpServer = None
self.button = QPushButton("Send", self)
self.button.move(50, 50)
self.clientConnection = None
self.tcpServer = QTcpServer(self)
PORT = 8000
address = QHostAddress('127.0.0.1')
if not self.tcpServer.listen(address, PORT):
print("cant listen!")
self.close()
return
self.tcpServer.newConnection.connect(self.dealCommunication)
print("listening for connection\n")
def sendText(self):
if not self.clientConnection:
print("I don't have an active connection\n")
return
text, result = QInputDialog.getText(self, "input", "text to send")
self.clientConnection.write(QByteArray(text.encode()))
self.clientConnection.write('\n'.encode())
def dealCommunication(self):
self.clientConnection = self.tcpServer.nextPendingConnection()
block = QByteArray()
out = QDataStream(block, QIODevice.WriteOnly)
out.writeUInt16(0)
message = "hi folks!\n"
message = bytes(message, encoding='ascii')
out.writeString(message)
out.device().seek(0)
out.writeUInt16(block.size() - 2)
self.clientConnection.disconnected.connect(self.clientConnection.deleteLater)
self.clientConnection.write(block)
#self.clientConnection.disconnectFromHost() <--- вот этого не надо
if __name__ == '__main__':
app = QApplication(sys.argv)
server = Server()
server.button.clicked.connect(server.sendText)
sys.exit(server.exec_())