python套接字流重定向实例汇总


Posted in Python onMarch 03, 2016

将套接字流重定向到标准输入或输出流

#!/usr/bin/env python3
"""
测试socket-stream 重定向模式
"""
import sys,os,time
from multiprocessing import Process
from socket import *
 
def initListenerSocket(port=50008,host=''):
    """ 
    初始化在服务器模式下调用者用于监听连接的套接字
    """
    sock=socket()
    try:
        sock.bind((host,port))
    except OSError as e:
        print('Address already in use')
        os._exit(1)
    sock.listen(5)
    conn,addr=sock.accept()
    return conn
 
def redirecOut(port=50008,host='localhost'):
    """ 
    在接受之前其他连接都失败,连接调用者标准输出流
    到一个套接字,这个套接字用于gui监听,在收听者启动后,启动调用者
    """
    sock=socket()
    try:
        sock.connect((host,port))
    except ConnectionRefusedError as e:
        print('connection refuse')
        os._exit(1)
    file=sock.makefile('w')
    sys.stdout=file
    return sock
 
def redirecIn(port=50008,host='localhost'):
    """ 
    连接调用者标准输入流到用于gui来提供的套接字
    """
    sock=socket()
    try:
        sock.connect((host,port))
    except ConnectionRefusedError as e:
        print('conenction refuse')
        os._exit(1)
    file=sock.makefile('r')
    sys.stdin=file
    return sock
 
def redirecBothAsClient(port=50008,host='localhost'):
    """
    在这种模式下,连接调用者标准输入和输出流到相同的套接字
    调用者对于服务器来说就是客户端:发送消息,接受响应答复
    """
    sock=socket()
    try:
        sock.connect((host,port))
    except ConnectionRefusedError as e:
        print('connection refuse')
        os._exit(1)
    ofile=sock.makefile('w')
    ifile=sock.makefile('r')
    sys.stdout=ofile
    sys.stdin=ifile
    return sock
 
def redirecBothAsServer(port=50008,host='localhost'):
    """
    在这种模式下,连接调用者标准输入和输出流到相同的套接字,调用者对于
    服务器来说就是服务端:接受消息,发送响应答复
    """
    sock=socket()
    try:
        sock.bind((host,port))
    except OSError as e:
        print('Address already in use')
        os._exit(1)
    sock.listen(5)
    conn,addr=sock.accept()
    ofile=conn.makefile('w')
    ifile=conn.makefile('r')
    sys.stdout=ofile
    sys.stdin=ifile
    return conn
 
def server1():
    mypid=os.getpid()
    conn=initListenerSocket()
    file=conn.makefile('r')
    for i in range(3):
        data=file.readline().rstrip()
        print('server %s got [%s]' %(mypid,data))
 
def client1():
    time.sleep(1)
    mypid=os.getpid()
    redirecOut()
    for i in range(3):
        print('client: %s:%s' % (mypid,i))
        sys.stdout.flush()
 
def server2():
    mypid=os.getpid()
    conn=initListenerSocket()
    for i in range(3):
        conn.send(('server %s got [%s]\n' %(mypid,i)).encode())
 
def client2():
    time.sleep(1)
    mypid=os.getpid()
    redirecIn()
    for i in range(3):
        data=input()
        print('client %s got [%s]]'%(mypid,data))
 
def server3():
    mypid=os.getpid()
    conn=initListenerSocket()
    file=conn.makefile('r')
    for i in range(3):
        data=file.readline().rstrip()
        conn.send(('server %s got [%s]\n' % (mypid,data)).encode())
 
def client3():
    time.sleep(1)
    mypid=os.getpid()
    redirecBothAsClient()
    for i in range(3):
        print('Client %s: %s' %(mypid,data))
        data=input()
        sys.stderr.write('client %s got [%s]\n' %(mypid,data))
 
def server4(port=50008,host='localhost'):
    mypid=os.getpid()
    sock=socket()
    try:
        sock.connect((host,port))
    ConnectionRefusedError as e:
        print('connection refuse')
        os._exit(1)
    file=sock.makefile('r')
    for i in range(3):
        sock.send(('server %s: %S\n' %(mypid,i)).encode())
        data=file.readline().rstrip()
        print('server %s got [%s]' %(mypid,data))
 
def client4():
    time.sleep(1)
    mypid=os.getpid()
    redirecBothAsServer()
    for i in range(3):
        data=input()
        print('client %s got [%s]'%(mypid,data))
        sys.stdout.flush()
 
def server5():
    mypid=os.getpid()
    conn=initListenerSocket()
    file=conn.makefile('r')
    for i in range(3):
        conn.send(('server %s:%s\n' %(mypid,i)).encode())
        data=file.readline().rstrip()
        print('server %s got [%s]' % (mypid,data))
 
def client5():
    mypid=os.getpid()
    s=redirecBothAsClient()
    for i in range(3):
        data=input()
        print('client %s got [%s]'%(mypid,data))
        sys.stdout.flush()
 
def main():
    server=eval('server'+sys.argv[1])
    client=eval('client'+sys.argv[1])
    Process(target=server).start()
    client()
 
if __name__=='__main__':
    main()
Python 相关文章推荐
详解python调度框架APScheduler使用
Mar 28 Python
利用Python查看目录中的文件示例详解
Aug 28 Python
python字符串与url编码的转换实例
May 10 Python
python训练数据时打乱训练数据与标签的两种方法小结
Nov 08 Python
Python内置random模块生成随机数的方法
May 31 Python
Python Django Cookie 简单用法解析
Aug 13 Python
Django 拆分model和view的实现方法
Aug 16 Python
Python中使用gflags实例及原理解析
Dec 13 Python
python plt可视化——打印特殊符号和制作图例代码
Apr 17 Python
Python 添加文件注释和函数注释操作
Aug 09 Python
Python脚本调试工具安装过程
Jan 11 Python
Django实现在线无水印抖音视频下载(附源码及地址)
May 06 Python
Python设计模式中单例模式的实现及在Tornado中的应用
Mar 02 #Python
Python使用设计模式中的责任链模式与迭代器模式的示例
Mar 02 #Python
详解Python设计模式编程中观察者模式与策略模式的运用
Mar 02 #Python
Python设计模式编程中解释器模式的简单程序示例分享
Mar 02 #Python
分析Python中设计模式之Decorator装饰器模式的要点
Mar 02 #Python
实例解析Python设计模式编程之桥接模式的运用
Mar 02 #Python
Python随机生成带特殊字符的密码
Mar 02 #Python
You might like
php预定义变量使用帮助(带实例)
2013/10/30 PHP
PHP访问数据库集群的方法小结
2016/03/14 PHP
php和vue配合使用技巧和方法
2019/05/09 PHP
php的扩展写法总结
2019/05/14 PHP
List Installed Software Features
2007/06/11 Javascript
可以用来调试JavaScript错误的解决方案
2010/08/07 Javascript
javascript中SetInterval与setTimeout的定时器用法
2015/08/24 Javascript
javascript的 {} 语句块详解
2016/02/27 Javascript
Node.js文件操作方法汇总
2016/03/22 Javascript
js实现精确到毫秒的倒计时效果
2016/08/05 Javascript
更靠谱的H5横竖屏检测方法(js代码)
2016/09/13 Javascript
javaScript实现复选框全选反选事件详解
2020/11/20 Javascript
Vue中自定义全局组件的实现方法
2017/12/08 Javascript
vue组件与复用详解
2018/04/08 Javascript
Vue js 的生命周期(看了就懂)(推荐)
2019/03/29 Javascript
Vue实现固定定位图标滑动隐藏效果
2019/05/30 Javascript
vue中watch和computed为什么能监听到数据的改变以及不同之处
2019/12/27 Javascript
Vue 禁用浏览器的前进后退操作
2020/09/04 Javascript
Python socket C/S结构的聊天室应用实现
2014/11/30 Python
在Python的Flask框架中使用日期和时间的教程
2015/04/21 Python
Python中函数的参数传递与可变长参数介绍
2015/06/30 Python
python对DICOM图像的读取方法详解
2017/07/17 Python
Python中列表list以及list与数组array的相互转换实现方法
2017/09/22 Python
Python在不同目录下导入模块的实现方法
2017/10/27 Python
django在接受post请求时显示403forbidden实例解析
2018/01/25 Python
python使用matplotlib绘制热图
2018/11/07 Python
解决tensorflow训练时内存持续增加并占满的问题
2020/01/19 Python
python matplotlib工具栏源码探析三之添加、删除自定义工具项的案例详解
2021/02/25 Python
联想新加坡官方网站:Lenovo Singapore
2017/10/24 全球购物
英国的屈臣氏:Boots博姿
2017/12/23 全球购物
Linux上比较文件的命令都有哪些
2013/09/28 面试题
MySQL面试题目集锦
2016/04/14 面试题
社区党总支书记先进事迹材料
2014/01/24 职场文书
个人三严三实对照检查材料思想汇报
2014/09/22 职场文书
检查机关党的群众路线个人整改措施
2014/10/04 职场文书
共青团员自我评价
2015/03/10 职场文书