码迷,mamicode.com
首页 > 编程语言 > 详细

python udp服务端-客户端

时间:2020-03-14 01:20:02      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:byte   ndt   waiting   connect   bytes   cti   code   import   send   

udp_server.py

import socket

u=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

addr=("0.0.0.0",9999)
u.bind(addr)
print("waiting for connection.........")
while True:
    data,ad=u.recvfrom(2024)
    if not data:
        print(f"{ad} have leaved")
    print(f"revice data from {ad}:{data.decode()}")
    d="I have revieved you data"
    n=u.sendto(d.encode(),ad)
    print(f"You have send {n} bytes")

u.close()

udp_client.py

import socket

uc=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)


while True:
    data=input("输入您要发送的消息:")
    addr=("127.0.0.1",9999)
    n=uc.sendto(data.encode(),addr)
    print("you have send data {} bytes".format(n))
    da=uc.recvfrom(2024)
    print("I have reviced :{}".format(da))
uc.close()

运行一个server和多个server

waiting for connection.........
revice data from (127.0.0.1, 57045):日照香炉生日宴
You have send 24 bytes
revice data from (127.0.0.1, 59622):遥看瀑布挂前川
You have send 24 bytes

 

python udp服务端-客户端

标签:byte   ndt   waiting   connect   bytes   cti   code   import   send   

原文地址:https://www.cnblogs.com/pfeiliu/p/12490110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!