首页 > 编程语言 > 详细

python udp服务端-客户端

时间:2020-03-14 01:13:54      阅读:88      评论:0      收藏:0      [点我收藏+]

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服务端-客户端

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!