1

I have a Client(C++) to Server (Python) Project.

The client sent a Message to the server, and each Message contains three attributes.

The Gui should show all the attributes over the screen. When the client sent the first message, everything works. But when he sent the next message I need to close the window, and when I do that it opens a new window and shows the following message, if I don't do that he doesn't show the new messages that received.

I suspect that app.exec_() stop the program from getting a new message like in this case, but I'm not sure. my question is :

  1. Is this really the case? And if so, where should I put the Thread?

  2. I never used QThread before, and I saw that we are doing Override for Run() and in the Run() method we put in all the logic, what logic I should put into my particular problem. you can find the full project here

Relevant code:

def recive(self):

        global income
        global table2

        msg = Payload(0, 0, 0)

        while (True):

            print('waiting for a connection..')
            conn, addr = self.My_socket.accept()
            print("connection has been established | " + repr(addr))
            logger.info("connection has been established | " + repr(addr))

            while conn:
                myThread = MyThread()

                buff = conn.recv(sizeof(msg))

                print("recv %d bytes" % sizeof(msg))
                payload_in = Payload.from_buffer_copy(buff)

                print(f"Received id={payload_in.id}, counter={payload_in.counter}, opcode={payload_in.opcode}")

                payload_out = payload_in

                self.opcode = payload_in.opcode

                if self.opcode == 1:
                    self.export()
                elif self.opcode == 2:
                    payload_out.counter += 1
                else:
                    logger.info("Unexpected opcode %d" % self.opcode)

                nsent = conn.send(payload_out)
                print("send %d bytes" % nsent)
                print("send id=%d, counter=%d, opcode=%d" % (payload_out.id,
                                                             payload_out.counter,
                                                             payload_out.opcode))
                self.setNewTable(payload_in, payload_out)

        print("Closing connection to client")
        print("----------------------------")

        sys.exit()

    def setNewTable(self,payload_in, payload_out):
            self.insertValues(table1, payload_in)
            self.insertValues(table2, payload_out)
            ex.show()
            app.exec_()

    def insertValues(self,table, payload):
            table.setItem(0, 1, QTableWidgetItem(str(payload.id)))
            table.setItem(1, 1, QTableWidgetItem(str(payload.counter)))
            table.setItem(2, 1, QTableWidgetItem(str(payload.opcode)))
TheTwo
  • 97
  • 7
  • Okay at a brief overview I see numerous issues that may be causing you problems my first and strongest suggestion is you need to classify all those functions because I do not think they are working the way you might be thinking that they are working. I will look at this in my spare time and see if I can fix the various issues I see with it but if you go through and classify it just post the new code (if it still does not work) and that could speed things up – Dennis Jensen Jul 22 '19 at 13:55
  • Dennis Jensen, I add a new version try to do my best. this is my first time facing OOP in python. The full code in the link above. – TheTwo Jul 22 '19 at 17:20
  • Okay I got the update and while I would - on a different forum - post the results piece-meal as I go this forum does not like that - so once I get the rework down I will post the full answer -- so far have the restructuring of the GUI done -- working on the sockets and thread part -- which btw is the part that interested me as its something I will need to do soon myself – Dennis Jensen Jul 22 '19 at 19:01
  • Thanks for the effort – TheTwo Jul 25 '19 at 16:15
  • The link to github where the supposed "server.py" would be, is not found there. Hence, posting answers on a different forum without link and pasting answer essentials makes no sense at all. Furthermore, the question is too broad and there are many examples here on SO and in the help manual of QT itself. Voting for removal of question. (From Review). – ZF007 Sep 14 '19 at 08:18

1 Answers1

0

I know couple of things about QThread ui think you need to use python signal and slot to update ui. refer following code

from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import datetime
import sys
import struct
import threading
import os
import datetime
import time
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)
class MySignal(QObject):
        signelforWritemsg=Signal(str)
class EchoThread(QThread):
    #def __init__(self,Inf_found1,inf_cleaned1,Auto_clean,timer,movie,Scan_btn,cancel_btn,status_text):
    def __init__(self,parent = None):
        QThread.__init__(self,parent)
        self.exiting = False
        self.signal = MySignal()

    def run(self):
        while True:
            scantimenow= datetime.datetime.now()
            scantime=scantimenow.strftime('%Y-%m-%d %H:%M:%S')
            print(scantime)
            self.signal.signelforWritemsg.emit(scantime)
            time.sleep(5)
class Ui_Clientserver(object):
    def setupUi(self, Clientserver):
        Clientserver.setObjectName(_fromUtf8("Clientserver"))
        Clientserver.resize(400, 300)
        self.label = QtGui.QLabel(Clientserver)
        self.label.setGeometry(QtCore.QRect(150, 70, 200, 200))
        self.label.setObjectName(_fromUtf8("label"))
        self.retranslateUi(Clientserver)

        self.thread = EchoThread()
        self.thread.start()
        self.thread.signal.signelforWritemsg.connect(self.signelforWritemsg)

    def signelforWritemsg(self,data):
        self.label.setText(_translate("Clientserver",str(data), None))
    def retranslateUi(self, Clientserver):
        Clientserver.setWindowTitle(_translate("Clientserver", "Clientserver", None))

        self.label.setText(_translate("Clientserver", "inProgess", None))
if __name__ == "__main__":
    import sys
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
    app = QtGui.QApplication(sys.argv)
    Clientserver = QtGui.QWidget()
    ui = Ui_Clientserver()
    ui.setupUi(Clientserver)
    Clientserver.show()
    sys.exit(app.exec_())
  • OP question is far from complete and server.py is lacking. That is the reason why nobody answers here. The essentials you've posted here are found in numerous examples here on SO. Lacking the server.py and still posting example... is likely effort in vain due to question "too broad". (From Review). – ZF007 Sep 14 '19 at 08:25