導航:首頁 > 編程語言 > pythonsocketlist

pythonsocketlist

發布時間:2024-11-20 04:45:52

『壹』 python中使用socket編程,如何能夠通過UDP傳遞一個列表類型的數據

Python中的 list 或者 dict 都可以轉成JSON字元串來發送,接收後再轉回來。


首先

importjson

然後,把 list 或 dict 轉成 JSON

json_string=json.mps(list_or_dict)

如果你用的是Python3,這里的 json_string 會是 str 類型(即Python2的unicode類型),可能需要編碼一下:

if type(json_string) == six.text_type:

json_string = json_string.encode('UTF-8')

用socket發送過去,例如

s.sendto(json_string,address)


對方用socket接收,例如

json_string,addr=s.recvfrom(2048)

把JSON轉成 list 或 dict

list_or_dict=json.loads(json_string)




下面是個完整的例子:


client.py

#!/usr/bin/envpython
#-*-coding:UTF-8-*-

importsocket
importjson
importsix

address=('127.0.0.1',31500)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mylist=[1,2,3,4,5,6,7,8,9,10]
json_string=json.mps(mylist)
iftype(json_string)==six.text_type:
json_string=json_string.encode('UTF-8')
s.sendto(json_string,address)
s.close()


server.py

#!/usr/bin/envpython
#-*-coding:UTF-8-*-

importsocket
importjson

address=('127.0.0.1',31500)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(address)
json_string,addr=s.recvfrom(2048)
mylist=json.loads(json_string)
print(mylist)
s.close()


請先運行server.py,再運行client.py

閱讀全文

與pythonsocketlist相關的資料

熱點內容
82一56的筒便演算法 瀏覽:404
數控機床fanuc編程 瀏覽:607
天刀mode不是內部或外部命令 瀏覽:854
長城c30壓縮機價格 瀏覽:1000
java打開圖片文件 瀏覽:409
跟程序員聊天聊到半夜 瀏覽:411
自己怎麼做app代碼 瀏覽:915
win7旗艦版進不去帶命令符 瀏覽:799
單片機溫度檢測電路 瀏覽:802
拼圖軟體不壓縮 瀏覽:656
紅袖添香小說源碼 瀏覽:624
erp加密工具在哪裡買 瀏覽:516
怎麼給qq群里的文件加密 瀏覽:762
androidsetbitmap 瀏覽:597
mt4反向編譯 瀏覽:201
sun伺服器命令 瀏覽:827
程序員同乘電梯 瀏覽:617
49乘以235的簡便演算法 瀏覽:673
新概念51單片機c語言教程光碟 瀏覽:262
伺服器分區如何選擇 瀏覽:354