-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchannel_helper.py
More file actions
72 lines (59 loc) · 1.59 KB
/
channel_helper.py
File metadata and controls
72 lines (59 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# ############################################################################
# client.py
# =========
# Author : Sepand KASHANI [sepand.kashani@epfl.ch]
# ############################################################################
import struct
import numpy as np
import io
def send_ndarray(sock, data):
"""
Send a NumPy array over the network.
Parameters
----------
sock : :py:class:`~socket.socket`
data : :py:class:`~numpy.ndarray`
"""
with io.BytesIO() as f:
np.save(f, data)
byte_data = f.getvalue()
# Pack message length
msg = struct.pack('>I', len(byte_data)) + byte_data
sock.sendall(msg)
def recv_ndarray(sock):
"""
Receive a NumPy array from the network.
Parameters
----------
sock : :py:class:`~socket.socket`
Returns
-------
data : :py:class:`~numpy.ndarray`
"""
# Extract message length
N_msg_raw = recv_bytes(sock, 4)
N_msg = struct.unpack('>I', N_msg_raw)[0]
msg = recv_bytes(sock, N_msg)
with io.BytesIO(msg) as f:
data = np.load(f)
return data
def recv_bytes(sock, N_byte):
"""
Receive bytes from the network.
Parameters
----------
sock : :py:class:`~socket.socket`
N_byte : int
Number of bytes to read.
Returns
-------
byte_data : bytes
"""
packet_size = 2 ** 12
packets, N_byte_read = [], 0
while N_byte_read < N_byte:
packet = sock.recv(min(packet_size, N_byte - N_byte_read))
packets.append(packet)
N_byte_read += len(packet)
byte_data = b''.join(packets)
return byte_data