Quantcast
Channel: Active questions tagged ubuntu - Stack Overflow
Viewing all articles
Browse latest Browse all 6511

socket.send stops working after first send in pysimplegui loop

$
0
0

I am trying to build a simple gui including a qr-code reader to send data to a remote server in python on Ubuntu for a school-project. I have set up a simple server to receive messages from the scanner via tcp/ip:

import socketfrom Crypto.Cipher import AESdef main():    # Server mit gegebener Adresse starten    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    server.bind(("192.168.1.40", 9999))    server.listen()    while True:        client, address = server.accept()        msg = client.recv(1024).decode('ASCII')        print(msg)        if __name__ == '__main__':    main()

If I run a simple test client all messages are received:

import socketclient = socket.socket()try:    client.connect(("192.168.1.40",9999))    for i in range(1,10):        client.send("\nHallo Server, ich bin dein Client und will was\n".encode('ASCII'))except:    print("Server nicht verfügbar\n\n")

and I get 9 messages printed row by row on the server.

The actual gui is

import PySimpleGUI as sgfrom pyzbar import pyzbarimport cv2import osimport socketimport mathfrom time import time, sleepfrom Crypto.Cipher import AESH1 = 0def read_qr():    vid = cv2.VideoCapture(0)    qr = False     while(not qr):        ret, frame = vid.read()        qr = pyzbar.decode(frame)            duration = .1    freq = 3000    os.system('play -nq -t alsa synth {} sine {}'.format(duration,freq))    qr = qr[0].data.decode().split(':::')    vid.release()    cv2.destroyAllWindows()    return qr    def si_msg(body):    global H1    H1 += 1    H2 = socket.gethostname().split('-')[2]    H3 = 0    H5, H4 = math.modf(time())    H6 = 2    H7 = len(body.encode('ASCII'))    si_msg = " ".join([str(H1), H2, str(H3), str(int(H4)), str(int(H5*10**8)), str(H6), str(H7), body])    return si_msgdef main():    sg.theme('PythonPlus')       status = 'Verbindung getrennt'    socket.setdefaulttimeout(2.5)    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    layout = [  [sg.Text('Server-Adresse:'),sg.Input(key = 'k_server', default_text='192.168.1.40:9999')],                [sg.Button('Server bestätigen')],                [sg.Text('Status:'), sg.Text(status, key = 'k_status')],                [sg.Exit()]]    window = sg.Window('Virtueller Login', layout)    while True:             event, values = window.read()        if event == sg.WIN_CLOSED or event == 'Exit':            break        elif event == 'Server bestätigen':            status = 'Verbindung zum Server wird hergestellt'            window['k_status'].update(status)            server = values['k_server'].split(':')            try:                client.connect((server[0],int(server[1])))                status = 'Verbindung hergestellt: ausgeloggt'                window['k_status'].update(status)            except:                status = 'Verbindungsversuch fehlgeschlagen'                window['k_status'].update(status)                sg.popup('FEHLER: Server nicht gefunden. Bitte prüfen Sie die Adresse oder wenden Sie sich an den Administrator')                continue        window.start_thread(lambda: read_qr(), 'Code gefunden')        if event == 'Code gefunden':            qr = values[event][0]            msg = si_msg(qr)            print(msg)            client.send(msg.encode('ASCII'))            sleep(2)    client.close()    window.close()if __name__ == '__main__':    main()

Running this main enables me to scan a qr-code/ barcode, which is successfully wrapped in the header (I have to make this ugly thing) and printed for each scan, iterating the scan-counter H1 with each scan. I am not getting any errors on client or server, but the server only receives the first scan.

To make sure it has nothing to do with the multithreading handled by pysimplegui I have omitted the lines

window.start_thread(lambda: read_qr(), 'Code gefunden')if event == 'Code gefunden':   qr = values[event][0]   msg = si_msg(qr)   print(msg)   client.send(msg.encode('ASCII'))   sleep(2)

and replaced them with a direct scan command (freezing the gui):

qr = read_qr()[0]msg = si_msg(qr)print(msg)client.send(msg.encode('ASCII'))

This let's me enable the connection, scan the code, send the message and then the loop seems to stop working and I can not scan anymore. I can press the connect-button of the gui a second time, thus "reconnecting" to the server (which was never disconnected?) scan again, but it wont send a message to the server and won't establish the connection a third time.

Alternatively, simply adding a second message manually does also not get send, this does not work either:

qr = read_qr()[0]msg = si_msg(qr)print(msg)client.send(msg.encode('ASCII'))sleep(0.5)msg = si_msg(qr)print(msg)client.send(msg.encode('ASCII'))

The counter iterates and is printed, but no second message is send, the connection seems lost, i can reconnect, scan again (without sending any of those messages) and that's it, again no third chance.

As I don't get any errors I am somewhat lost on this. I don't think it has anything to do with pysimplegui, as the consecutive manual messages don't get send either, but I have no Idea and would be happy for any help...


Viewing all articles
Browse latest Browse all 6511

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>