oatty8867
oatty8867

Reputation: 43

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte in Socket Programming

Hello so I've been doing a Python Socket Programming. What I want to do is send a string variable called "option" to server.

This is the Client code

option = "4"
client.send(option.encode())

I got the 'error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte'.

So here is my server code.

option = client.recv(512).decode()

The option in server should received a String that has a value as "4" but like I said I got an error. Could anyone know how to solve this ? Thanks in advance.

Upvotes: 0

Views: 1824

Answers (2)

oatty8867
oatty8867

Reputation: 43

I figured it out ! so I changed from this

option = client.recv(512).decode()

to this

option = client.recv(1).decode()

and it's worked ! so my conclusion is Client trying to send a String to server. What I want to send to server is "4" so the size of block that Client try to send is 1.

I'm not sure but this worked for me.

Upvotes: 0

tdelaney
tdelaney

Reputation: 77337

Since network programming tyically envolves multiple machines that can have different encodings, one should define the encoding for a protocol. It can either be a single encoding everyone must use (a very good choice these days) or there needs to be a way to negotiate the encoding in the protocol itself.

In your case you could just hard code it:

option = "4"
client.send(option.encode(encoding="utf-8"))

and

option = client.recv(512).decode(encoding="utf-8")

This still has a glaring bug. recv doesn't receive things in the exact size of the sender. If your encoded characters is, say, 3 bytes, the receiver may receive a partial character. That means you need some way of demarking strings so that both sides know where a given character or string ends. But that's a different kettle of fish.

There are many existing protocols out there to deal with message boundaries, encoding, and etc. HTTP, XMLRPC, Zeromq are just a few. These can be a lot easier than rolling your own solution.

Upvotes: 1

Related Questions