zoukankan      html  css  js  c++  java
  • 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>>>
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    2.GO-可变参数函数、匿名函数和函数变量
    1.Go-copy函数、sort排序、双向链表、list操作和双向循环链表
    第四章、Go-面向“对象”
    第三章、Go-内建容器
    第二章、Go-基础语法
    第一章、Go安装与Goland破解
    arthas使用分享
    redis如何后台启动
    java.io.IOException: Could not locate executable nullinwinutils.exe in the Hadoop binaries
    安装redis出现cc adlist.o /bin/sh:1:cc:not found的解决方法
  • 原文地址:https://www.cnblogs.com/JacquelineQA/p/13835641.html
Copyright © 2011-2022 走看看