How to implement app communication port

后端 未结 1 1037
无人共我
无人共我 2021-01-26 06:24

Saving the code below as application.py allows me to run a process that when started shows a simple QDialog with a QLabel:

python applica

相关标签:
1条回答
  • 2021-01-26 06:41

    Below is a working solution designed around SocketServer's TPCServer and BaseRequestHandler Classes.

    This implementation utilizes QThread Class.

    application.py

    import SocketServer
    
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    
    IP, PORT = '127.0.0.1', 62236
    
    app = QApplication([])
    
    
    class Emitter(QObject):
        signal = pyqtSignal(str)
    
    
    class Handler(SocketServer.BaseRequestHandler):
        emitter = Emitter()
    
        def handle(self):
            self.emitter.signal.emit(self.request.recv(1024))
    
    
    class Thread(QThread):
        def __init__(self, target, parent=None):
            QThread.__init__(self, parent)
            self.target = target
    
        def run(self):
            while True:
                self.target()
    
    
    class Dialog(QDialog):
        def __init__(self, parent=None):
            super(Dialog, self).__init__(parent)
    
            Handler.emitter.signal.connect(self.onEmit)
            self.server = SocketServer.TCPServer((IP, PORT), Handler)
    
            thread = Thread(target=self.server.handle_request)
            thread.start()
    
            self.setLayout(QVBoxLayout())
            self.label = QLabel('somewhere over the rainbow')
            self.layout().addWidget(self.label)
            self.show()
    
        def closeEvent(self, event):
            self.server.server_close()
            event.accept()
    
        def onEmit(self, arg):
            self.label.setText(str(arg))
    
    
    dialog = Dialog()
    app.exec_()
    

    client.py

    import socket
    
    IP, PORT = '127.0.0.1', 62236
    
    def send(data):
        SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        SOCKET.connect((IP, PORT))
        SOCKET.send(data)
        SOCKET.close()
    
    for i in range(2, 1000):
        send('data %07d'%i)
    
    send(raw_input("input:\t"))
    

    With threading.Thread use SocketServer.TCPServer.serve_forever method instead of SocketServer.TCPServer.handle_request:

        import threading
        thread = threading.Thread(target=self.server.serve_forever)
        thread.start()
    
    0 讨论(0)
提交回复
热议问题