0

I've been trying to learn socket programming and my aim is to send request from client to the server, also send back a response from server to client despite client's request. In the code, i am trying to send \x02\x03\x35\x36\x37\x01\x00\05\x02\x75 and \x02\x05\x01\x35\x36\x01\x01\05\x02\x76 datas but in my output i see \x02\x03567\x01\x00\x05\x02u and \x02\x05\x0156\x01\x01\x05\x02v instead of them. Am i doing something wrong? Here are my codes:

server.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1236))

s.listen(5)
print("Waiting for connection...")

server_message = b"\x02\x05\x01\x35\x36\x01\x01\05\x02\x76"

while True:
    clientsocket, addr = s.accept()
    print(f"Successfully connected with client from {addr}", addr)

    client_message = clientsocket.recv(1024)            # Get request from the client.
    print("Request from the Client:", client_message)

    if client_message.__eq__(b"\x02\x03\x35\x36\x37\x01\x00\05\x02\x75"): # If request is appropriate for response then;
        clientsocket.send(server_message)           # Send response to the client.
        print("Response to the Client:", server_message)

    clientsocket.close()

client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1236))

client_message = b"\x02\x03\x35\x36\x37\x01\x00\05\x02\x75"

try:
    s.send(client_message)      # Send request to the server.

    server_message = s.recv(1024)       # Get response from the server.

    print("Request to the Server:", client_message)
    print("Response from the Server:", server_message)

    s.close()

except socket.error as error_message:
    print("Server is not working", error_message)
1

1 Answer 1

1

You're not doing anything wrong, and they only seem different. As you will quickly see see if you do this:

>>> version1 = b"\x02\x03\x35\x36\x37\x01\x00\05\x02\x75"
>>> version2 = b'\x02\x03567\x01\x00\x05\x02u'
>>> version1==version2
True

The reason is because \x35 is the byte value of the character 5, and when Python displays bytestrings it renders any printable character as that character, and if it is not printable but there is a string escape, then it renders it as the string escape, so \x0d which is a carriage return will appear as \r, and it only renders a byte as a hex escape as a last resort. There are various reasons for this, but one of the most obvious is that bytestrings often contain character data, and b'Hello world' is friendlier than b'\x48\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.