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

发布于 2024-11-30 11:50:46 字数 1180 浏览 1 评论 0 原文

是否可以使用Python通过UDP套接字发送数组?我正在使用 Python 2.5 并尝试发送一个简单的数组,但它不起作用。它可以成功发送数组,但是当我尝试使用数组的一项来打印它时,程序崩溃了。我不确定错误是什么,因为我采取了预防措施将数据转换为数组,但它不起作用。希望我尽可能清楚地解释这个问题。我将不胜感激的帮助!

# 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()

Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. 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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

不如归去 2024-12-07 11:50:46

eval 所做的事情与你想象的完全不同。

要通过网络发送数据,您需要将其序列化为字节数组,然后反序列化回来。在Python中,大多数对象的序列化可以通过pickle模块完成:

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

反序列化:

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

eval is doing something completely different than what you think.

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:

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])
新一帅帅 2024-12-07 11:50:46

我个人会使用 tostring< /a> 和 fromstring 因为内置序列化方法是 快很多倍 和 pickle 可能不支持 NaN、Inf 和其他未定义的值。

I would personally use tostring and fromstring since the built-in serialization methods are many times faster and pickle may not support NaN, Inf and other undefined values.

诗化ㄋ丶相逢 2024-12-07 11:50:46

你试图通过套接字发送一个python对象,这是正常的,它不起作用,你不能在套接字中发送对象,对象不是数据,它们是给定编程语言中某些数据的表示。您需要将对象“转换”为数据,并根据另一套接字端的数据重新创建对象。实现此目的的一种方法是使用 pickle 模块。

在客户端,您“pickle”对象:

data = pickle.dumps(my_array)

在服务器端,您“unpickle”接收到的数据:

my_array = pickle.loads(received_data)

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. 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.

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)
时光无声 2024-12-07 11:50:46

您可以尝试pickle数组。 Pickle 是一个用于编码和解码 Python 对象的 Python 库。它可以做更多的事情,但绝对足以完成您的任务:

在发送方,您将对象 pickle 为字符串:

pickled_string = pickle.dumps(a)

在接收方,您unpickle对象:

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

You could try to pickle the array. Pickle is a python library to en- and decode python objects. 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:

pickled_string = pickle.dumps(a)

on the receiver side you unpickle the object:

a = pickle.loads(received_string)
# a is now your sent array
佼人 2024-12-07 11:50:46

自从提出这个问题以来已经有一段时间了,但我认为值得分享 jsonsocket。它使得通过套接字发送字符串、列表和字典变得非常容易。它可以有效地处理大量数据。并且您不需要进行任何手动序列化/反序列化。在底层,它在客户端将数据序列化为 JSON 字符串,并在服务器上将其反序列化。

It has been a while since this question was asked, but I thought it's worth sharing the jsonsocket library. 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.

梦途 2024-12-07 11:50:46

如果您不需要专门的 UDP,请尝试 zmqObjectExchanger (https://github.com/ZdenekM/zmq_object_exchanger )。它包装 pickle 和 zmq 以通过 TCP 传输 python 对象。

If you don't need UDP specifically, try zmqObjectExchanger (https://github.com/ZdenekM/zmq_object_exchanger). It wraps pickle and zmq to transfer python objects over TCP.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文