通过 Socket 发送和接收数组

Sending and Receiving arrays via Sockets(通过 Socket 发送和接收数组)

本文介绍了通过 Socket 发送和接收数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 "
",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 "
Received message '", L[1],"'"

# Close socket
UDPSock.close()

推荐答案

eval 做的事情与你想的完全不同.

eval is doing something completely different than what you think.

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

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

反序列化:

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

这篇关于通过 Socket 发送和接收数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:通过 Socket 发送和接收数组

基础教程推荐