python通訊端流重新導向執行個體匯總

來源:互聯網
上載者:User
將通訊端流重新導向到標準輸入或輸出資料流

#!/usr/bin/env python3"""測試socket-stream 重新導向模式"""import sys,os,timefrom multiprocessing import Processfrom 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()
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.