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 初始化多维数组代码
Sep 06 Python
Python自动化测试工具Splinter简介和使用实例
May 13 Python
Python网络爬虫出现乱码问题的解决方法
Jan 05 Python
简单了解Django应用app及分布式路由
Jul 24 Python
Win10里python3创建虚拟环境的步骤
Jan 31 Python
超全Python图像处理讲解(多模块实现)
Apr 13 Python
使用Jupyter notebooks上传文件夹或大量数据到服务器
Apr 14 Python
python 实现读取csv数据,分类求和 再写进 csv
May 18 Python
python 线程的五个状态
Sep 22 Python
python空元组在all中返回结果详解
Dec 15 Python
python3 kubernetes api的使用示例
Jan 12 Python
Python 无限级分类树状结构生成算法的实现
Jan 21 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
php4的彩蛋
2006/10/09 PHP
PHP 应用程序的安全 -- 不能违反的四条安全规则
2006/11/26 PHP
解析php函数method_exists()与is_callable()的区别
2013/06/21 PHP
thinkPHP多域名情况下使用memcache方式共享session数据的实现方法
2016/07/21 PHP
PHP实现的XML操作类【XML Library】
2016/12/29 PHP
bindParam和bindValue的区别以及在Yii2中的使用详解
2018/03/12 PHP
让IE8支持DOM 2(不用框架!)
2009/12/31 Javascript
JavaScript验证18位身份证号码最后一位正确性的实现代码
2014/08/07 Javascript
jQuery实现漂亮实用的商品图片tips提示框效果(无图片箭头+阴影)
2016/04/16 Javascript
Google 地图API资料整理及详细介绍
2016/08/06 Javascript
js实现可旋转的立方体模型
2016/10/16 Javascript
微信小程序 教程之wxapp视图容器 scroll-view
2016/10/19 Javascript
ThinkJS中如何使用MongoDB的CURD操作
2016/12/13 Javascript
underscore之Collections_动力节点Java学院整理
2017/07/10 Javascript
vue单文件组件无法获取$refs的问题
2020/06/24 Javascript
零基础写python爬虫之抓取百度贴吧代码分享
2014/11/06 Python
教大家玩转Python字符串处理的七种技巧
2017/03/31 Python
Python外星人入侵游戏编程完整版
2020/03/30 Python
Python字符编码与函数的基本使用方法
2017/09/30 Python
python3 pandas 读取MySQL数据和插入的实例
2018/04/20 Python
基于Django框架利用Ajax实现点赞功能实例代码
2018/08/19 Python
解决pandas .to_excel不覆盖已有sheet的问题
2018/12/10 Python
在Python中COM口的调用方法
2019/07/03 Python
基于CentOS搭建Python Django环境过程解析
2020/08/24 Python
解决html5中video标签无法播放mp4问题的办法
2017/05/07 HTML / CSS
英国综合网上购物商城:The Hut
2018/07/03 全球购物
德国自然时尚和有机产品购物网站:Waschbär
2019/05/29 全球购物
安全生产活动月方案
2014/03/09 职场文书
酒店爱岗敬业演讲稿
2014/09/02 职场文书
单位租车协议书
2015/01/29 职场文书
2015年党建工作目标责任书
2015/05/08 职场文书
音乐课外活动总结
2015/05/09 职场文书
2015年测量员工作总结
2015/05/23 职场文书
法律意见书范本
2015/06/04 职场文书
《圆的面积》教学反思
2016/02/19 职场文书
使用CSS实现百叶窗效果示例代码
2023/05/07 HTML / CSS