• Python网络编程


    Python网络编程 - UDP编程
     
    用例1:服务器端和客户端1对多通信
     
    服务器端
    import socket
     
    # 创建服务器端套接字
    sk = socket.socket(type=socket.SOCK_DGRAM)
     
    # 把地址绑定到套接字
    ip_port = ('127.0.0.1',8080)
    sk.bind(ip_port)
    print(socket.gethostname())
     
    while True:
        # 接收客户端信息
        info,addr = sk.recvfrom(1024)
     
        # 打印客户端信息
        print(info.decode('utf-8'))
        print(addr)
     
        # 发送信息
        message = input('Server>>>').encode('utf-8')
        sk.sendto(message,addr)
     
    # 关闭服务器套接字
    sk.close()
     
    客户端1
    import socket
     
    # 创建客户端套接字
    sk = socket.socket(type=socket.SOCK_DGRAM)
    ip_port = ('127.0.0.1',8080)
     
    while True:
        # 信息发送
        message = input('Client1>>>').encode('utf-8')
        sk.sendto(message,ip_port)
     
        # 信息接收
        info,addr = sk.recvfrom(1024)
     
        # 信息打印
        print(info.decode('utf-8'))
        print(addr)
     
    # 关闭客户端套接字
    sk.close()                
     
    客户端2
    import socket
     
    # 创建客户端套接字
    sk = socket.socket(type=socket.SOCK_DGRAM)
    ip_port = ('127.0.0.1',8080)
     
    while True:
        # 信息发送
        message = input('Client2>>>').encode('utf-8')
        sk.sendto(message,ip_port)
     
        # 信息接收
        info,addr = sk.recvfrom(1024)
     
        # 信息打印
        print(info.decode('utf-8'))
        print(addr)
     
    # 关闭客户端套接字
    sk.close()                
     
    运行:
    在Pycham中打开Terminal1,运行服务器程序,分别和客户端程序1,2聊天。
    (python3_for_training) U:ProjectPython_TrainingPytho_Basic>python TcpServerSimple.py
    MSI
    大家好,我是客户端1
    ('127.0.0.1', 54612)
    Server>>>你好,客户端1
    大家好,我是客户端2;
    ('127.0.0.1', 54613)
    Server>>>你好客户端2
     
    在Pycham中打开Terminal2,运行客户端程序1,和服务器程序聊天。
    (python3_for_training) U:ProjectPython_TrainingPytho_Basic>python TcpClientSimple.py
    Client1>>>大家好,我是客户端1
    你好,客户端1
    ('127.0.0.1', 8080)
    Client1>>>
     
    在Pycham中打开Terminal3,运行客户端程序2,和服务器程序聊天。
    (python3_for_training) U:ProjectPython_TrainingPytho_Basic>python TcpClientSimple.py
    Client1>>>大家好,我是客户端2
    你好,客户端2
    ('127.0.0.1', 8080)
    Client1>>>
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    古传拳经拳法秘要
    JAVA漏洞扫描工具之墨菲安全for IDEA
    PostgreSql 加密和解密
    DirBuster使用介绍
    Increase the default timeout value for the Service Control Manager in the Registry
    一文说透 MySQL JSON 数据类型(收藏)
    电脑常识——host文件修改(屏蔽网站或解开屏蔽)zz
    SQL语法学习记录(三)
    SQL语法学习记录(一)
    SQL语法学习记录(二)
  • 原文地址:https://www.cnblogs.com/JacquelineQA/p/13835641.html
Copyright © 2020-2023  润新知