python udp服务端-客户端

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

 

posted @ 2020-03-14 00:18  腹肌猿  阅读(344)  评论(0编辑  收藏  举报