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操作json数据的一个简单例子
Apr 17 Python
Python实现KNN邻近算法
Jan 28 Python
Tornado高并发处理方法实例代码
Jan 15 Python
Django实现登录随机验证码的示例代码
Jun 20 Python
python运行时强制刷新缓冲区的方法
Jan 14 Python
Python+Selenium使用Page Object实现页面自动化测试
Jul 14 Python
Python获取一个用户名的组ID过程解析
Sep 03 Python
flask 使用 flask_apscheduler 做定时循环任务的实现
Dec 10 Python
Python语言异常处理测试过程解析
Jan 08 Python
Python逐行读取文件内容的方法总结
Feb 14 Python
Python爬虫实现vip电影下载的示例代码
Apr 20 Python
Ubuntu20下的Django安装的方法步骤
Jan 24 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中通过smtp发邮件的类,测试通过
2007/01/22 PHP
用PHP程序实现支持页面后退的两种方法
2008/06/30 PHP
PHP中用接口、抽象类、普通基类实现“面向接口编程”与“耦合方法”简述
2011/03/23 PHP
php number_format() 函数通过千位分组来格式化数字的实现代码
2013/08/06 PHP
php截取中文字符串不乱码的方法
2013/12/25 PHP
Laravel 4 初级教程之视图、命名空间、路由
2014/10/30 PHP
php和editplus正则表达式去除空白行
2015/04/17 PHP
php使用curl获取header检测开启GZip压缩的方法
2018/08/15 PHP
JavaScript事件列表解说
2006/12/22 Javascript
JavaScript类继承及实例化的方法
2015/07/25 Javascript
纯JavaScript基于notie.js插件实现消息提示特效
2016/01/18 Javascript
使用基于Node.js的构建工具Grunt来发布ASP.NET MVC项目
2016/02/15 Javascript
js获取地址栏中传递的参数(两种方法)
2017/02/08 Javascript
js脚本编写简单刷票投票系统
2017/06/27 Javascript
详解Node 定时器
2018/02/26 Javascript
layui下拉列表select实现可输入查找的方法
2019/09/28 Javascript
[01:36]DOTA2完美大师赛趣味视频之与队友相处的十万个技巧
2017/11/19 DOTA
python self,cls,decorator的理解
2009/07/13 Python
python绘图库Matplotlib的安装
2014/07/03 Python
python模块之StringIO使用示例
2015/04/08 Python
PyCharm在win10的64位系统安装实例
2017/11/26 Python
对Python3中的print函数以及与python2的对比分析
2018/05/02 Python
利用Anaconda简单安装scrapy框架的方法
2018/06/13 Python
解决python读取几千万行的大表内存问题
2018/06/26 Python
TensorFlow车牌识别完整版代码(含车牌数据集)
2019/08/05 Python
在win64上使用bypy进行百度网盘文件上传功能
2020/01/02 Python
python next()和iter()函数原理解析
2020/02/07 Python
python如何更新包
2020/06/11 Python
Pandas的Apply函数具体使用
2020/07/21 Python
通过实例了解Python异常处理机制底层实现
2020/07/23 Python
微信小程序canvas实现水平、垂直居中效果
2020/02/05 HTML / CSS
美国购买汽车零件网站:Buy Auto Parts
2018/04/02 全球购物
结婚喜宴主持词
2014/03/14 职场文书
网吧消防安全责任书
2014/07/29 职场文书
python编写函数注意事项总结
2021/03/29 Python
MIME类型中application/xml与text/xml的区别介绍
2022/01/18 HTML / CSS