Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to send numpy array over python socket

  • Hey , Good day !
  • I implement a simple program to send a numpy array over python sockets

This is server.py

import socket
import numpy as np

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1024))
s.listen(5)
print('Server is ready...')

while True:
    client, adr = s.accept()
    print(f'Connection to {adr} established')
    myarray = np.array([[1,2],[3,4]])
    client.send(myarray)
    client.close()

This is client.py

import socket

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

getarray = s.recv(100)
print(getarray)
  • I want to send myarray in server.py to client.py

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • I want to get the myarray in client.py 100% similar to the myarray in server.py

  • **But, When I run server.py and client.py , client.py’s output is this .. **

b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'

  • I don’t know what is the encoding method (asci or utf-8 to decode that code)
  • How can I decode it ?

Thank you !

>Solution :

You could use pickle to encode the array object into bytes, and then send that.
Although depending on the size of the array you may need to change the way you receive it, s.recv() will only get a certain number of bytes, so you would need to send the size of the array in bytes over first, and then repeat s.recv until you have the entire array. pickle.dumps(obj) will return the byte stream of the object, and pickle.loads(obj) will return the original object once all of it is received.

Hope that helps 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading