• python3 UDP协议下的socket


    ---------------------------------------udp_server.py---------------------------------------
    
    # coding:utf-8
    import socket
    
    udp_server = socket.socket(type=socket.SOCK_DGRAM)  # 创建socket对象,DGRAM:datagram 数据报文,UDP协议通信
    ip_port = ("127.0.0.1", 8001)
    udp_server.bind(ip_port)  # 绑定IP和端口号
    from_client_msg, client_addr = udp_server.recvfrom(1024)  # 接收来自客户端的消息
    print("来自客户端的消息:", from_client_msg.decode("utf-8"))
    server_input = input(">>>: ").strip()
    udp_server.sendto(server_input.encode("utf-8"), client_addr)  # 给客户端发送消息
    udp_server.close()  # 关闭连接
    
    
    ---------------------------------------udp_client.py---------------------------------------
    
    # coding:utf-8
    import socket
    
    udp_client = socket.socket(type=socket.SOCK_DGRAM)  # 创建socket对象,DGRAM:datagram 数据报文,UDP协议通信
    ip_port = ("127.0.0.1", 8001)
    client_input = input(">>>: ").strip()
    udp_client.sendto(client_input.encode("utf-8"), ip_port)  # 给服务端发送消息
    from_server_msg, server_addr = udp_client.recvfrom(1024)  # 接收来自服务端的消息,最大为1024B
    print("来自服务端的消息:", from_server_msg.decode("utf-8"))
    udp_client.close()  # 关闭连接
    
    
    UDP练习的需求是这样的:
    1、服务端需要提供的服务有:接收消息(时间格式的字符串)、将我的本地的时间转换成接收到的消息的格式(也就是个时间格式的字符串)、发回给客户端。
    2、客户端自行想一下怎么写。
    
    ---------------------------------------practice_udp_server.py---------------------------------------
    
    # coding:utf-8
    import socket
    import time
    
    udp_server = socket.socket(type=socket.SOCK_DGRAM)
    ip_port = ("127.0.0.1", 8001)
    udp_server.bind(ip_port)
    from_client_msg, addr = udp_server.recvfrom(1024)
    print("来自客户端的消息:", from_client_msg.decode("utf-8"))
    udp_server.sendto(time.strftime("%Y-%m-%d %X").encode("utf-8"), addr)
    udp_server.close()
    
    
    ---------------------------------------practice_udp_client.py---------------------------------------
    
    # coding:utf-8
    import socket
    
    udp_client = socket.socket(type=socket.SOCK_DGRAM)
    ip_port = ("127.0.0.1", 8001)
    client_input = input("格式化时间: ").strip()
    udp_client.sendto(client_input.encode("utf-8"), ip_port)
    from_server_msg, addr = udp_client.recvfrom(1024)
    print("来自服务端的消息:", from_server_msg.decode("utf-8"))
    udp_client.close()
  • 相关阅读:
    Python基础语法 第2节课(数据类型转换、运算符、字符串)
    python基础语法 第5节课 ( if 、 for )
    python基础语法 第4节课 (字典 元组 集合)
    Python基础语法 第3节课 (列表)
    A. Peter and Snow Blower 解析(思維、幾何)
    C. Dima and Salad 解析(思維、DP)
    D. Serval and Rooted Tree (樹狀DP)
    C2. Balanced Removals (Harder) (幾何、思維)
    B. Two Fairs 解析(思維、DFS、組合)
    D. Bash and a Tough Math Puzzle 解析(線段樹、數論)
  • 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10927264.html
Copyright © 2020-2023  润新知