1
I’m new to Python, and I’m trying to set up a server socket for message exchange (like a telnet) to communicate with a client. The problem I’m facing is that this client has its own protocol, and I need to get the server to send the messages in a compatible way. I need the messages to be sent to the customer in the following format:
b'\x01\x08\x00Testando'
The problem is that I am not able to produce the signal ' ' as it should be, the second byte ' x08' should be according to the message size (In hexadecimal) and for this I created a variable 'h' to calculate, and then concatenate the string, but I cannot concatenate, Python gives me errors. I tried to concatenate in the following ways:
'\x01\x'+h+'\x00' # Deu erro.
r'\x01\x'+h+'\x00' # Não deu erro, mas ficou com duas barras '\\'.
str('\x01\x'+h+'\x00') # Outra vez um erro.
It did not work, if I put two signs of ' ', then it accepts, but the sending to the customer is wrong, containing two signals and it does not accept this format.
b'\\x01\\x08\\x00Testando' # O cliente não aceita assim.
I tried to use Unicode ' u', but it resulted in the same sequence above, with two signs of ' '. I noticed that this error only occurs when I try to concatenate the string with the variable, if I put the value manually as in the first code presented, it accepts without problems, but as I need to do this dynamically it becomes unviable. If I concatenate the variable without the ' ' ' signal in the byte before it, Python does not accuse errors, but if I put the sign it does not accept.
'\x01x'+h+'\x00' # Aceitou sem problemas, porém faltando o sinal.
Another thing I noticed is that it requires that after x, you have two characters, if you have less it is error too, for example:
'\x01\x0\x00Testando' # Faltando uma casa no segundo byte da erro.
'\x01\x08\x00Testando' # Feito manualmente, funciona perfeito.
To send this string to the client, the socket requires it to be in bytes, and I tested two ways:
b'\x01\x'+h+'\x00'
bytes('\x01\x'+h+'\x00', 'iso-8859-1')
I tried with and without iso coding. I would like to know if anyone has any idea what I can do to be able to assemble the string in the format that is required by the client. Ah, the encoding the client works with is 'iso-8859-1'.
Thank you very much!
You tried to convert the h byte before concatenating? (with the method bytes.fromhex())? Type:
b'\x01' + bytes.fromhex(h) + b'\x00'
– Gomiero
That’s just what I needed, it worked perfectly, thank you very much! :D
– Gau