简体   繁体   English

通过套接字发送和接收数组

[英]Sending and Receiving arrays via Sockets

Is it possible to send an array through UDP Sockets using Python? 是否可以使用Python通过UDP套接字发送数组? I am using Python 2.5 and trying to send a simple array but it's not working. 我正在使用Python 2.5并尝试发送一个简单的数组,但它不起作用。 It can send the array successfully but when I try to print it with an item of the array the program crashes. 它可以成功发送数组,但是当我尝试使用数组项打印它时,程序崩溃了。 I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. 我不确定错误是什么,因为我采取了将数据转换为数组的预防措施,但它不起作用。 Hope I explained the problem as clearly as possible. 希望我尽可能清楚地解释问题。 I would appreciate the help! 我很感激你的帮助!

# Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()



# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()

eval is doing something completely different than what you think. eval正在做一些与你想象完全不同的事情。

To send data over network, you need to serialize it into an array of bytes, then deserialize it back. 要通过网络发送数据,您需要将其序列化为一个字节数组,然后反序列化 In Python, serialization of most objects can be done via pickle module: 在Python中,大多数对象的序列化可以通过pickle模块完成:

if (UDPSock.sendto( pickle.dumps(a), addr)):

Deserialization: 反序列化:

data,addr = UDPSock.recvfrom(buf)
L = pickle.loads(data)
print repr(L) # prints array('i', [1, 3, 2])

我个人会使用tostringfromstring因为内置的序列化方法要快很多倍,而pickle 可能不支持 NaN,Inf和其他未定义的值。

You're trying to send a python object through a socket, it is normal that it doesn't work, you can't send objects in a socket, objects are not data, they are the representation of some data in a given programming language. 你试图通过套接字发送一个python对象,它是不正常的,你不能在套接字中发送对象,对象不是数据,它们是给定编程语言中某些数据的表示是正常的。 You need to "translate" your object to data and re-create the object from the data on the other socket's side. 您需要将对象“转换”为数据,并从另一个套接字的数据重新创建对象。 One way to do this would be with the pickle module. 一种方法是使用pickle模块。

On the client side, you "pickle" the object: 在客户端,你“挑选”对象:

data = pickle.dumps(my_array)

And on the server side, you "unpickle" the received data: 在服务器端,您“取消”收到的数据:

my_array = pickle.loads(received_data)

You could try to pickle the array. 你可以尝试pickle阵列。 Pickle is a python library to en- and decode python objects. Pickle是一个用于编码和解码python对象的python库。 It is able to do much more, but it is definitely sufficient to fulfill your task: 它能够做得更多,但它绝对足以完成你的任务:

on the sender side you pickle the object to a string: 在发送方,您将对象pickle为字符串:

pickled_string = pickle.dumps(a)

on the receiver side you unpickle the object: 在接收器端你unpickle对象:

a = pickle.loads(received_string)
# a is now your sent array

It has been a while since this question was asked, but I thought it's worth sharing the jsonsocket library . 自问这个问题以来已经有一段时间了,但我认为值得分享jsonsocket It makes it really easy to send strings, lists and dictionaries over sockets. 它使得通过套接字发送字符串,列表和字典变得非常容易。 It can handle big amounts of data efficiently. 它可以有效地处理大量数据。 And you don't need to do any manual serialization/deserialization. 而且您不需要进行任何手动序列化/反序列化。 Under the hood, it serializes the data as JSON strings on the client, and deserializes it on the server. 在引擎盖下,它将数据序列化为客户端上的JSON字符串,并在服务器上对其进行反序列化。

If you don't need UDP specifically, try zmqObjectExchanger ( https://github.com/ZdenekM/zmq_object_exchanger ). 如果您不需要UDP,请尝试使用zmqObjectExchanger( https://github.com/ZdenekM/zmq_object_exchanger )。 It wraps pickle and zmq to transfer python objects over TCP. 它包装pickle和zmq以通过TCP传输python对象。

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

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