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设置检查点简单实现代码
Jul 01 Python
python返回昨天日期的方法
May 13 Python
Python实现截屏的函数
Jul 26 Python
浅谈Python NLP入门教程
Dec 25 Python
详谈python中冒号与逗号的区别
Apr 18 Python
Python3爬虫之urllib携带cookie爬取网页的方法
Dec 28 Python
Python socket模块实现的udp通信功能示例
Apr 10 Python
python虚拟环境完美部署教程
Aug 06 Python
Python ORM编程基础示例
Feb 02 Python
python剪切视频与合并视频的实现
Mar 03 Python
Python unittest单元测试框架实现参数化
Apr 29 Python
Python和Bash结合在一起的方法
Nov 13 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 SPL标准库之数据结构栈(SplStack)介绍
2015/05/12 PHP
UPUPW 更新 64 位 Apache 系列 PHP 7.0 正式版
2015/12/08 PHP
Yaf框架封装的MySQL数据库操作示例
2019/03/06 PHP
laravel5.5安装jwt-auth 生成token令牌的示例
2019/10/24 PHP
Javascript 的addEventListener()及attachEvent()区别分析
2009/05/21 Javascript
Mootools 1.2教程 Fx.Tween的使用
2009/09/15 Javascript
IE6/7 and IE8/9/10(IE7模式)依次隐藏具有absolute或relative的父元素和子元素后再显示父元素
2011/07/31 Javascript
js 延迟加载 改变JS的位置加快网页加载速度
2012/12/11 Javascript
E3 tree 1.6在Firefox下显示问题的修复方法
2013/01/30 Javascript
javascript处理表单示例(javascript提交表单)
2014/04/28 Javascript
JS实现判断碰撞的方法
2015/02/11 Javascript
js 判断一组日期是否是连续的简单实例
2016/07/11 Javascript
用js控件div的滚动条,让它在内容更新时自动滚到底部的实现方法
2016/10/27 Javascript
Angular1.x自定义指令实例详解
2017/03/01 Javascript
js调用刷新界面的几种方式
2017/05/03 Javascript
微信小程序 action-sheet 反馈上拉菜单简单实例
2017/05/11 Javascript
ZeroClipboard.js使用一个flash复制多个文本框
2017/06/19 Javascript
微信小程序picker组件下拉框选择input输入框的实例
2017/09/20 Javascript
微信小程序动态增加按钮组件
2018/09/14 Javascript
nodejs读取本地中文json文件出现乱码解决方法
2018/10/10 NodeJs
解决layer.prompt无效的问题
2019/09/24 Javascript
Javascript实现贪吃蛇小游戏(含详细注释)
2020/10/23 Javascript
python中datetime模块中strftime/strptime函数的使用
2018/07/03 Python
解决Python3中的中文字符编码的问题
2018/07/18 Python
查看python下OpenCV版本的方法
2018/08/03 Python
如何通过50行Python代码获取公众号全部文章
2019/07/12 Python
Django  ORM 练习题及答案
2019/07/19 Python
wxpython绘制圆角窗体
2019/11/18 Python
python 遗传算法求函数极值的实现代码
2020/02/11 Python
python使用docx模块读写docx文件的方法与docx模块常用方法详解
2020/02/17 Python
python爬虫开发之Request模块从安装到详细使用方法与实例全解
2020/03/09 Python
深入剖析webstorage[html5的本地数据处理]
2016/07/11 HTML / CSS
巴西最大的体育用品商城:Netshoes巴西
2016/11/29 全球购物
UML设计模式笔试题
2014/06/07 面试题
自荐信模板大全
2015/03/27 职场文书
clear 万能清除浮动(clearfix:after)
2023/05/21 HTML / CSS