简体   繁体   English

Python-在以太网数据包中发送/接收一个numpy数组

[英]Python - send/receive a numpy array in an Ethernet Packet

I need to set up a network to transfer a numpy array from a host computer to a client computer. 我需要建立一个网络,以将numpy数组从主机计算机传输到客户端计算机。 This can be as simple as possible except I have to use 16 bit integers. 除非我必须使用16位整数,否则这可以尽可能简单。 Am I doing it right? 我做对了吗? Are there better functions/commands I should be using? 我应该使用更好的功能/命令吗? (Win7, 64bit, Python 2.7) So far, it seems to work but I am a total noob to networking and I haven't found a decent tutorial that explains how all this fits together. (Win7、64位,Python 2.7)到目前为止,它似乎可以正常工作,但是我对网络一无所知,但是我还没有找到一个不错的教程来解释所有这些如何结合在一起。 (Please suggest one) Thanks! (请提出一个建议)谢谢!

server.py server.py

import socket, time, numpy as np
myDict = {1:1, 2:2, 3:3}
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
while 1:
    data = np.array(myDict.values(), dtype = np.int16).flatten()
    s.sendto(data, ('<broadcast>',5252))
    time.sleep(1)

client.py client.py

import socket, numpy as np
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 5252))
data = np.empty((1,6), dtype = np.int16)
s.recv_into(data)
print data

You are using datagram sockets (UDP) to transfer your data. 您正在使用数据报套接字(UDP)传输数据。 UDP is best effort service and you are not guaranteed that every datagram you send will be delivered at the remote end. UDP是一种尽力而为的服务,不能保证您发送的每个数据报都会在远程端传递。

An alternative is to use TCP, but the you will need to serialize your numpy data before sending it over the socket and then deserialize it when you receive it. 一种替代方法是使用TCP,但是您需要先对numpy数据进行序列化,然后再通过套接字发送,然后在收到时反序列化。

If you are fine with using unreliable UDP transfers, then what you are doing now is OK. 如果您可以使用不可靠的UDP传输,那么现在您可以做什么。

Edit: When using broadcast - you are basically sending same piece of data to all devices in your directly attached network. 编辑:使用广播时-您基本上是将相同的数据发送到直接连接的网络中的所有设备。 Any device listening to UDP port 5252 will be able to receive data that you are sending. 任何监听UDP端口5252的设备都将能够接收您正在发送的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM