Python—网络通信编程之udp通信编程

服务端

from socket import *
import sys
from time import ctime
#从命令行传入ip地址和端口
# python3 udp_server.py 172.60.50.42 8888
if len(sys.argv)<3:
    print("argv is error,")
HOST = sys.argv[1]
PORT = int(sys.argv[2])
ADDR = (HOST,PORT)
BUFFERSIZE = 1024
1.创建数据报套接字
  sockfd = socket(AF_INET,SOCK_DGRAM)
2.绑定地址
  sockfd.bind(ADDR)
3.收发消息
  while True:
      data,addr = sockfd.recvfrom(BUFFERSIZE)
      print("recv from %s:%s"%(addr,data.decode()))
      sockfd.sendto(("[%s]接受到消息"%ctime()).encode(),addr)
4.关闭套接字
  sockfd.close()

  

客户端

你可能感兴趣的:(Python—网络通信编程之udp通信编程)