manu3d
manu3d

Reputation: 1081

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.

Upvotes: 0

Views: 35

Answers (2)

Markus
Markus

Reputation: 316

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)

Upvotes: 1

manu3d
manu3d

Reputation: 1081

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.

Upvotes: 0

Related Questions