1

I'm trying to send a custom object via sockets in Python. My object is defined as:

packet = Packet.Packet(MAGIC_NUMBER,0,sender_next,packet_size,local_buffer)
port_out.send(packet)

But I am getting an error of: builtins.TypeError: a bytes-like object is required, not 'Packet'

I've seen previous posts about using .encode() for str types but how do I do it for a custom object like this? Do I need to make a encode method?

3
  • 1
    You need a way of converting to bytes. For strings that is .encode(). For your Packet object it's whatever you choose to call it. Commented Sep 4, 2017 at 2:23
  • Possible duplicate of how to send objects through python? Commented Sep 4, 2017 at 4:22
  • How do I create this .encode() function. Commented Sep 14, 2017 at 9:23

1 Answer 1

1

You can use pickle

import pickle

packet = Packet.Packet(MAGIC_NUMBER,0,sender_next,packet_size,local_buffer)
port_out.send(pickle.dumps(packet))

https://pymotw.com/3/pickle/index.html

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.