I'm new to Python, and am trying to set up a socket server for exchanging messages (like a telnet) for communication with a client. The problem I am facing is that this client has its own protocol, and I need to have the server send the messages in a compatible way. I need the messages to be sent to the client in the following format:
b'\x01\x08\x00Testando'
The problem is that I can not produce the signal '\' as it should, the second byte '\ x08' should be according to the size of the message (In hexadecimal) and for this I created a variable 'h' to calculate, and then do the concatenation in the string, but I can not concatenate, Python returns me errors.
I've tried concatenating 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 client 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 as above, with two '\' signs. 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 it dynamically it becomes impractical. If I concatenate the variable without the '\' sign in the byte before it, Python does not acknowledge errors, but if I put the signal it will not accept.
'\x01x'+h+'\x00' # Aceitou sem problemas, porém faltando o sinal.
Another thing I noticed is that it requires that after x, have two characters, if it has less it accuses 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 encoding. I'd like to know if anyone has any idea what I can do to get the string set up in the format that is required by the client. Oh, the coding the client works with is 'iso-8859-1'.
Thank you!