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

 更新时间:2016年03月03日 08:48:41   投稿:hebedich  
套接字是一种具有之前所说的“通信端点”概念的计算网络数据结构。相当于电话插口,没它无法通信,这个比喻非常形象。今天我们就来汇总一下套接字流重定向的实例

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

#!/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实现自动化的sql延时注入

    python实现自动化的sql延时注入

    这篇文章主要为大家详细介绍了如何基于python实现自动化的sql延时注入脚本,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-12-12
  • Pandas缺失值填充 df.fillna()的实现

    Pandas缺失值填充 df.fillna()的实现

    本文主要介绍了Pandas缺失值填充 df.fillna()的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • python中使用矢量化替换循环详解

    python中使用矢量化替换循环详解

    矢量化是在数据集上实现 (NumPy) 数组操作的技术。在后台,它将操作一次性应用于数组或系列的所有元素(不同于一次操作一行的“for”循环)。
    2023-01-01
  • 教你如何用python开发一款数字推盘小游戏

    教你如何用python开发一款数字推盘小游戏

    这篇文章主要介绍了教你如何用python开发一款数字推盘小游戏,文中有非常详细的代码示例,喜对欢玩小游戏的或者正在学习python小游戏开发的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-04-04
  • matplotlib bar()实现百分比堆积柱状图

    matplotlib bar()实现百分比堆积柱状图

    这篇文章主要介绍了matplotlib bar()实现百分比堆积柱状图,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • python pywinauto使用过程及问题小结

    python pywinauto使用过程及问题小结

    在pywinauto库中,uia即UIAutomation,是微软提供的用于用户界面自动化测试和辅助功能访问的技术框架,UIAutomation支持自动化脚本与各种UI元素交互,本文给大家介绍python pywinauto使用过程及问题小结,感兴趣的朋友一起看看吧
    2024-10-10
  • Python+Pygame实现神庙逃亡游戏

    Python+Pygame实现神庙逃亡游戏

    这篇文章主要为大家介绍了如何利用Python和Pygame动画制作一个神庙逃亡类似的小游戏。文中的示例代码讲解详细,感兴趣的小伙伴可以动手尝试一下
    2022-05-05
  • Python读写unicode文件的方法

    Python读写unicode文件的方法

    这篇文章主要介绍了Python读写unicode文件的方法,涉及Python针对文件的读取及编码操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • python机器学习基础特征工程算法详解

    python机器学习基础特征工程算法详解

    这篇文章主要为大家介绍了python机器学习基础特征工程的算法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2021-11-11
  • python如何使用双线性插值计算网格内数据

    python如何使用双线性插值计算网格内数据

    这篇文章主要介绍了python如何使用双线性插值计算网格内数据问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08

最新评论