Home > Software engineering >  how to send numpy array over python socket
how to send numpy array over python socket

Time:04-02

  • 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

  • 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 !

CodePudding user response:

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 :)

  • Related