python:Socket编程(五):基于udp协议编程

python:Socket编程(五):基于udp协议编程

#-*-coding:utf-8-*-
#基于udp协议的套接字编程与基于tcp协议的套接字编程有部分不同
#基于udp协议的编程,没有链接一说;看下面代码

#服务端:

from socket import *

ip_port=("127.0.0.1",8080)
buffer_size=1024
udp_service=socket(AF_INET,SOCK_DGRAM)
#基于udp协议的套接字建立的对象不同于tcp协议的,tcp这里的参数:SOCK_STREAM,即:tcp数据流
#而,upd这里的参数:SOCK_DGRAM,即:数据报
#但是,tcp\udp都有一个AF_INET参数,即:基于网络
udp_service.bind(ip_port)
while True:
    msg,addr=udp_service.recvfrom(buffer_size)
    #基于udp协议的套接字,收消息使用recvfrom()方法,
    # 且收到的内容为tuple类型,内容包括:客户端真实想发的信息,客户端地址
    print(msg.decode("utf-8"))
    udp_service.sendto("大家好才是真的好!".encode("utf-8"),addr)
    # 基于udp协议的套接字,发消息使用sendto(内容,地址)方法;
udp_service.close()
#-*-coding:utf-8-*-
#基于udp协议的套接字编程
#客户端

from socket import *

ip_port=("127.0.0.1",8080)
buffer_size=1024

client=socket(AF_INET,SOCK_DGRAM)

while True:
    client_msg=input(">>>:").strip()
    if not client_msg:continue
    client.sendto(client_msg.encode("utf-8"),ip_port)
    msg,addr=client.recvfrom(buffer_size)
    print(msg.decode("utf-8"))
    # print(addr)


client.close()