博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 网络编程之socket udp
阅读量:6984 次
发布时间:2019-06-27

本文共 3494 字,大约阅读时间需要 11 分钟。

hot3.png

 

一、环境

    windows10 + python3.6

二、code

#!/usr/bin/env python3# coding=utf-8import argparse, random, socket, sysMAX_BYTES = 65535def server(interface, port):    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    sock.bind((interface, port))    print('Listening at', sock.getsockname())    while True:        data, address = sock.recvfrom(MAX_BYTES)        if random.random() < 0.5:            print('Pretending to drop packet from {}'.format(address))            continue        text = data.decode('ascii')        print('The client at {} says {!r}'.format(address, text))        message = 'You data was {} bytes long'.format(len(data))        sock.sendto(message.encode('ascii'), address)def client(hostname, port):    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    hostname = sys.argv[2]    sock.connect((hostname, port))    print('Client socket name is {}'.format(sock.getsockname()))    delay = 0.1  # seconds    text = 'This is another message'    data = text.encode('ascii')    while True:        sock.send(data)        print('Waiting up to {} seconds for a reply'.format(delay))        sock.settimeout(delay)        try:            data = sock.recv(MAX_BYTES)     # recv() is block        except socket.timeout:            '''exponential backoff(指数退避)'''            delay *= 2  # wait even longer for the next request            if delay > 2.0:                raise RuntimeError('I think the server is down')        else:            break   # we are done, and can stop looping    print('The server says {!r}'.format(data.decode('ascii')))if __name__ == '__main__':    choices = {'client': client, 'server': server}    parser = argparse.ArgumentParser(description='Send and receive UDP,'                                     'pretending packets are often dropped')    parser.add_argument('role', choices=choices, help='Which role to take')    parser.add_argument('host', help='interface the server listens at;'                        'host the client sends to')    parser.add_argument('-p', metavar='PORT', type=int, default=1060,                        help="UDP port (default 1060)")    args = parser.parse_args()    function = choices[args.role]    function(args.host, args.p)

 

udp广播

#!/usr/bin/env python3# coding=utf-8import argparse, socketBUFSIZE = 65535def server(interface, port):    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    sock.bind((interface, port))    print('Listening for datagrams at {}'.format(sock.getsockname()))    while True:        data, address = sock.recvfrom(BUFSIZE)        text = data.decode('ascii')        print('The client at {} says: {!r}'.format(address, text))def client(network, port):    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)    text = 'Broadcast datagram!'    sock.sendto(text.encode('ascii'), (network, port))if __name__ == '__main__':    choices = {'client': client, 'server': server}    parser = argparse.ArgumentParser(description='Send,receive UDP broadcast')    parser.add_argument('role', choices=choices, help='wich role to take')    parser.add_argument('host', help='interface the server listens at;'                                     'network the client sends to')    parser.add_argument('-p', metavar='port', type=int, default=1060,                        help='UDP port (default 1060)')    args = parser.parse_args()    function = choices[args.role]    function(args.host, args.p)

 

转载于:https://my.oschina.net/medivhxu/blog/1581560

你可能感兴趣的文章
windows下安装rabbitMQ
查看>>
20个优秀的移动(iPhone)网站设计案例
查看>>
CentOS 6.3安装Nginx开启目录浏览、下载功能
查看>>
oracle登陆认证方式
查看>>
FMDB/SQLCipher数据库管理
查看>>
cocos_python
查看>>
关于安装oracle 11G R2 for Windows X64问题
查看>>
springmvc 重定向传递参数
查看>>
tomcat实现session集群及tomcat+memcached共享session存储(四)
查看>>
线性时间排序--桶排
查看>>
Three.js学习笔记
查看>>
ceph-deploy部署bluestore
查看>>
AIX修改系统时间 命令
查看>>
Window_Open详解
查看>>
金蝶CLOUD索引碎片超过80的表重建索引
查看>>
PHP案例 网页计数器设计
查看>>
算出两个经纬度的距离(米)
查看>>
我的友情链接
查看>>
树莓派2代B model 上手初体验,不用显示器,Python GPIO 点亮一颗LED
查看>>
Kotlin 4 构造,对象,修饰符,关键字,委托
查看>>