热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

套接字是一种具有之前所说的“通信端点”概念的计算网络数据结构。相当于电话插口,没它无法通信,这个比喻非常形象。今天我们就来汇总一下套接字流重定向的实例
将套接字流重定向到标准输入或输出流

#!/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()

推荐阅读
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • Python字典推导式及循环列表生成字典方法
    本文介绍了Python中使用字典推导式和循环列表生成字典的方法,包括通过循环列表生成相应的字典,并给出了执行结果。详细讲解了代码实现过程。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • 本文介绍了Python版Protobuf的安装和使用方法,包括版本选择、编译配置、示例代码等内容。通过学习本教程,您将了解如何在Python中使用Protobuf进行数据序列化和反序列化操作,以及相关的注意事项和技巧。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了brain的意思、读音、翻译、用法、发音、词组、同反义词等内容,以及脑新东方在线英语词典的相关信息。还包括了brain的词汇搭配、形容词和名词的用法,以及与brain相关的短语和词组。此外,还介绍了与brain相关的医学术语和智囊团等相关内容。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • Echarts图表重复加载、axis重复多次请求问题解决记录
    文章目录1.需求描述2.问题描述正常状态:问题状态:3.解决方法1.需求描述使用Echats实现了一个中国地图:通过选择查询周期&#x ... [详细]
  • 本文详细介绍了解决全栈跨域问题的方法及步骤,包括添加权限、设置Access-Control-Allow-Origin、白名单等。通过这些操作,可以实现在不同服务器上的数据访问,并解决后台报错问题。同时,还提供了解决second页面访问数据的方法。 ... [详细]
author-avatar
2502910的
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有