是否可以通過使用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()
This Works,Thank you! – dawnoflife