简体   繁体   中英

What is the simplest client/server pair that can be written in Python?

What is the simplest client/server pair that can be written in Python?

Let's restrict the user case to a simple echo functionality, where the client sends a message to the server, the server echoes it to its own standard output and the client eventually shuts down the server. But let's require for the client and server to live in separate processes.

Depends on what is simple? You can raise the abstraction and go HTTP. You have to know/lern frameworks, but it is shorter.

pip install flask
pip install requests

Server using flask:

from flask import Flask
app = Flask(__name__)

@app.route('/<msg>')
def hello_world(msg):
    return msg

app.run()

Client using requests:

import requests

print(requests.get("http://localhost:5000/hello").text)

Server.py:

from threading import Thread
from multiprocessing import Queue
from multiprocessing.managers import BaseManager

class QueueManager(BaseManager):
    pass

messagingQueue = Queue()

QueueManager.register('get_queue', callable=lambda: messagingQueue)
manager = QueueManager(address=('127.0.0.1', 50000), authkey=b'myAuthKey')
server = manager.get_server()

listenerThread= Thread(target=server.serve_forever)
listenerThread.daemon = True
listenerThread.start()

while True: 

    data = messagingQueue.get()
    if data == "STOP":
        break

    print(data)

Client.py:

from multiprocessing.managers import BaseManager

class QueueManager(BaseManager): pass

QueueManager.register('get_queue')
m = QueueManager(address=('127.0.0.1', 50000), authkey=b'myAuthKey')
m.connect()

queue = m.get_queue()
queue.put('Hello World!!')
queue.put('STOP')

Running these two files in separate shells with:

prompt> python -u Server.py

and

prompt> python -u Client.py

Seems to be as small as it can get. Removing the STOP functionality, relying simply on a keyboard interrupt, would make it even smaller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM