python创建udp服务端和客户端

发布时间:2019-03-04 15:58:43编辑:auto阅读(1990)

    1.udp服务端server

     1 from socket import *
     2 from time import ctime
     3 
     4 HOST = ''
     5 PORT = 8888
     6 BUFSIZ = 1024
     7 ADDR = (HOST, PORT)
     8 
     9 udpSerSock = socket(AF_INET, SOCK_DGRAM)
    10 udpSerSock.bind(ADDR)
    11 
    12 while True:
    13     print('waiting for message...')
    14     data, addr = udpSerSock.recvfrom(BUFSIZ)
    15 
    16     content = '[%s] %s' % (bytes(ctime(), "utf-8"), data)
    17     udpSerSock.sendto(content.encode("utf-8"), addr)
    18     print('...received from and returned to:', addr)
    19 
    20 udpSerSock.close()

     

     

     

    2.udp客户端client

     1 from socket import *
     2 
     3 HOST = 'localhost'
     4 PORT = 8888
     5 BUFSIZ = 1024
     6 ADDR = (HOST, PORT)
     7 
     8 udpCliSock = socket(AF_INET, SOCK_DGRAM)
     9 
    10 while True:
    11     data = input('> ')
    12     if not data:
    13         break
    14 
    15     udpCliSock.sendto(data.encode("utf-8"), ADDR)
    16     data, ADDR = udpCliSock.recvfrom(BUFSIZ)
    17     if not data:
    18         break
    19     print(data)
    20 
    21 udpCliSock.close()

     

关键字