创建UDP套接字流程

"""
 UDP套接字服务端
"""
from socket import *

# 创建数据报套接字

sockfd = socket(AF_INET,SOCK_DGRAM)

# 绑定地址
server_addr = ('0.0.0.0',8888)
sockfd.bind(server_addr)

# 消息收发
while True:
    data,addr = sockfd.recvfrom(1024)
    print("收到的消息:",data.decode())
    sockfd.sendto(b'Thank',addr)

# 关闭套接字
sockfd.close()
"""
  UDP套接字 客户端

"""
from socket import *

# 服务器地址
HOST = '176.215.155.159'
PORT = 8888
ADDR = (HOST,PORT)

# 创建套接字
sockfd = socket(AF_INET,SOCK_DGRAM)

# 收发消息
while True:
    data = input("Mas>>")
    if not data:
        break
    sockfd.sendto(data.encode(),ADDR)
    msg,addr = sockfd.recvfrom(1024)
    print("From server:",msg.decode())

# 关闭套接字
sockfd.close()
"""
 套接字常用属性
"""
from socket import *

# 创建一个TCP套接字
s = socket()

s.bind(('176.215.155.170',8886))
s.listen(3)
# c,addr = s.accept()
print("地址类型:",s.family)
print("套接字类型:",s.type)
print("绑定地址:",s.getsockname())
print("描述符:",s.fileno())
print("客户端地址:",s.getpeername())

你可能感兴趣的:(创建UDP套接字流程)