0

I was a socket TCP server in python using asyncore. My handle_read function is:

def handle_read(self):

    data = self.recv(50)

    '''interpretar os comandos:
    operação: Ligar/Desligar Bomba, Ligar/Desligar Aquecedor, Alterar velocidade da bomba
    Modo: trocar de modo automático para remoto
    Armazenamento: ativar ou desativar o armazenamento de dados para o trend e
    também apagar dados
    '''
    if len(data) < 2:  #comandos digitais
        try:
            process_commands(data)
        except Exception as err:
            print(str(err))
    else: #comando analogico
        try:
            ld = json.loads(data.decode('utf-8'))
            bytescommand = pack('f',ld['pump_speed'])
            bus.write_block_data(arduinoAddress,53,list(bytescommand))
        except Exception as err:
            print(str(err))
        finally:
            pass

Look, i test the data received to execute functions. But when a client disconnect, the program returns:

"char format requires a bytes object of lenght 1"

This indicates that handle_read function executes when client disconnect. It's normal? How i proccess the situation?

Thanks a lot!

1 Answers1

0

That is a normal call. When the peer closes its socket (or simply shutdowns it with SH_WR) a read call returns immediately with 0 bytes.

So your handle_read should be prepared for that end of file on the socket:

def handle_read(self):

...
if len(data) == 0: # EOF on input socket
    pass           # or add disconnection processing...
elif len(data) < 2:  #comandos digitais
    ...
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252