導航:首頁 > 編程語言 > 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相關的資料

熱點內容
大學文件夾怎麼刪除 瀏覽:665
linux科研軟體 瀏覽:550
ue4打包編譯著色器 瀏覽:772
雲伺服器可以在手機上登錄嗎 瀏覽:673
網游腳本為什麼要連接伺服器 瀏覽:4
程序員發展路線圖 瀏覽:318
手機語音加密會議 瀏覽:587
冰與火pdf 瀏覽:416
為什麼叫我買阿里雲伺服器 瀏覽:470
加密貨幣征稅一覽表 瀏覽:959
llc編譯器 瀏覽:922
數控可編程電阻器 瀏覽:757
培訓app源碼 瀏覽:431
phpcurl啟用 瀏覽:533
ubuntu圖形編程 瀏覽:441
jar包啟動命令 瀏覽:680
java數組一維轉二維 瀏覽:500
office批量轉pdf 瀏覽:185
boss直聘程序員多少薪 瀏覽:633
編程字母代表什麼 瀏覽:954