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()

 

相关文章:

  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-16
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2022-01-16
  • 2021-05-15
  • 2021-09-12
相关资源
相似解决方案