SoFunction
Updated on 2024-10-29

Summary of python socket stream redirection examples

Summary of python socket stream redirection examples

Updated March 03, 2016 08:48:41 PM by hebedich
A socket is a computing network data structure with the concept of a "communication endpoint" as previously described. It is the equivalent of a telephone jack, without which communication is impossible, which is a very good analogy. Today we will summarize the socket stream redirection example

Redirect socket streams to standard input or output streams

#!/usr/bin/env python3
"""
Testing socket-stream redirection mode
"""
import sys,os,time
from multiprocessing import Process
from socket import *
 
def initListenerSocket(port=50008,host=''):
    """
    Initialize the socket used by the caller in server mode to listen for connections
    """
    sock=socket()
    try:
        ((host,port))
    except OSError as e:
        print('Address already in use')
        os._exit(1)
    (5)
    conn,addr=()
    return conn
 
def redirecOut(port=50008,host='localhost'):
    """
    All other connections fail before acceptance, connecting the caller's standard output stream
    to a socket that is used for gui listening, which starts the caller after the listener has started
    """
    sock=socket()
    try:
        ((host,port))
    except ConnectionRefusedError as e:
        print('connection refuse')
        os._exit(1)
    file=('w')
    =file
    return sock
 
def redirecIn(port=50008,host='localhost'):
    """
    Connects the caller's standard input stream to the socket used to provide the gui.
    """
    sock=socket()
    try:
        ((host,port))
    except ConnectionRefusedError as e:
        print('conenction refuse')
        os._exit(1)
    file=('r')
    =file
    return sock
 
def redirecBothAsClient(port=50008,host='localhost'):
    """
    In this mode, the connection caller streams standard input and output to the same socket
    The caller is a client to the server: sends a message and receives a response in reply
    """
    sock=socket()
    try:
        ((host,port))
    except ConnectionRefusedError as e:
        print('connection refuse')
        os._exit(1)
    ofile=('w')
    ifile=('r')
    =ofile
    =ifile
    return sock
 
def redirecBothAsServer(port=50008,host='localhost'):
    """
    In this mode, the connection caller standard input and output flows to the same socket, and the caller is a server to the
    server is the server side: it accepts messages and sends response replies
    """
    sock=socket()
    try:
        ((host,port))
    except OSError as e:
        print('Address already in use')
        os._exit(1)
    (5)
    conn,addr=()
    ofile=('w')
    ifile=('r')
    =ofile
    =ifile
    return conn
 
def server1():
    mypid=()
    conn=initListenerSocket()
    file=('r')
    for i in range(3):
        data=().rstrip()
        print('server %s got [%s]' %(mypid,data))
 
def client1():
    (1)
    mypid=()
    redirecOut()
    for i in range(3):
        print('client: %s:%s' % (mypid,i))
        ()
 
def server2():
    mypid=()
    conn=initListenerSocket()
    for i in range(3):
        (('server %s got [%s]\n' %(mypid,i)).encode())
 
def client2():
    (1)
    mypid=()
    redirecIn()
    for i in range(3):
        data=input()
        print('client %s got [%s]]'%(mypid,data))
 
def server3():
    mypid=()
    conn=initListenerSocket()
    file=('r')
    for i in range(3):
        data=().rstrip()
        (('server %s got [%s]\n' % (mypid,data)).encode())
 
def client3():
    (1)
    mypid=()
    redirecBothAsClient()
    for i in range(3):
        print('Client %s: %s' %(mypid,data))
        data=input()
        ('client %s got [%s]\n' %(mypid,data))
 
def server4(port=50008,host='localhost'):
    mypid=()
    sock=socket()
    try:
        ((host,port))
    ConnectionRefusedError as e:
        print('connection refuse')
        os._exit(1)
    file=('r')
    for i in range(3):
        (('server %s: %S\n' %(mypid,i)).encode())
        data=().rstrip()
        print('server %s got [%s]' %(mypid,data))
 
def client4():
    (1)
    mypid=()
    redirecBothAsServer()
    for i in range(3):
        data=input()
        print('client %s got [%s]'%(mypid,data))
        ()
 
def server5():
    mypid=()
    conn=initListenerSocket()
    file=('r')
    for i in range(3):
        (('server %s:%s\n' %(mypid,i)).encode())
        data=().rstrip()
        print('server %s got [%s]' % (mypid,data))
 
def client5():
    mypid=()
    s=redirecBothAsClient()
    for i in range(3):
        data=input()
        print('client %s got [%s]'%(mypid,data))
        ()
 
def main():
    server=eval('server'+[1])
    client=eval('client'+[1])
    Process(target=server).start()
    client()
 
if __name__=='__main__':
    main()

  • python
  • socket

Related articles

  • Python application tools of the cache mechanism of the wonderful use of details

    In Python applications, the use of caching can significantly improve performance and reduce resource consumption, this article describes in detail how to implement the caching mechanism in Python, interested partners can follow the editor to learn together!
    2023-12-12
  • An Introduction to Generators and Iterators in Python

    This article introduces the Python generator and iterator in the relevant information, the text explains the very detailed, to help you better understand and learn, interested friends can learn about the
    2020-06-06
  • Save crawled data to mysql using scrapy (to prevent duplication)

    This article introduces you to the use of scrapy will crawl to the data saved to mysql (to prevent duplication) of the relevant information, the text through the sample code describes the very detailed, on everyone's learning or work has a certain reference to the learning value of the need for friends below to take a look at it together.
    2018-03-03
  • Example of a Python implementation of a plain Bayesian classifier

    This article introduces the Python implementation of the simple Bayesian classifier, combined with specific examples of the form of analysis based on Python implementation of the simple Bayesian classifier related to the definition and use of skills, need friends can refer to the following
    2018-01-01
  • Python write phonebook to realize the function of adding, deleting, changing and checking.

    This article is mainly for you to introduce in detail the Python phonebook written to achieve the function of adding, deleting, changing and checking the relevant information, interested friends can refer to it
    2016-05-05
  • Example of guiding the user to specify a selection of documents on the Python command line

    This article introduces the Python command line to guide the user to specify the choice of document examples, there is a need for friends can refer to reference, I hope to be able to help, I wish you more progress, an early promotion and salary increase!
    2023-11-11
  • PyInstaller for Win Installation and Usage Tutorial

    pyinstaller is a very simple package python py file library, this article introduces the PyInstaller-Win installation and use of tutorials, this article through a combination of process examples to give you a very detailed, you need friends can refer to the next!
    2019-12-12
  • Python to PPT to achieve the method of inserting tables and pictures in detail

    This article will take you to learn how to insert tables and pictures in the PPT as well as in the form of inserting content, the text of the sample code explains the details, interested partners can follow the editor to learn together!
    2022-05-05
  • Implementation of creating Gif motion graphics using matplotlib

    This article introduces the use of matplotlib to create the realization of the Gif motion picture, the text through the sample code is very detailed, for everyone's learning or work has a certain reference value of learning, the need for friends below along with the editors to study together to learn it!
    2022-04-04
  • python Seven Examples of Email Content Delivery Methods

    This article mainly introduces the python seven methods of sending e-mail content examples, the need for friends can refer to the following
    2014-04-04

Latest Comments