You are here

Test servers

When developing client / server applications, it's often useful to be able to test each side on its own. It's even more useful when one of the two sides doesn't provide any log capability.

This article provides very simple test servers implemented in Python, aimed at helping client development.

Multithreaded TCP server

Our first server is a multithreaded TCP server. Code is copied from here. It is only (very very) slightly modified, to ensure that it receives incoming connection requests on any local network interface.

Received data is echoed back to the client.

Beware: TCP is a stream-oriented protocol, not a message-oriented protocol. So the code below would not be acceptable in a production environment. Anyway, for test purposes, there is no real problem

from socket import *
import thread

BUFF = 1024
HOST = ''
#HOST = '127.0.0.1'# must be input parameter @TODO
PORT = 7714 # must be input parameter @TODO
def response(key):
return 'Server response: ' + key

def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
print repr(addr) + ' recv:' + repr(data)
clientsock.send(response(data))
print repr(addr) + ' sent:' + repr(response(data))
if "close" == data.rstrip(): break # type 'close' on client console to close connection from the server side

clientsock.close()
print addr, "- closed connection" #log on console

if __name__=='__main__':
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(ADDR)
serversock.listen(5)
while 1:
print 'waiting for connection... listening on port', PORT
clientsock, addr = serversock.accept()
print '...connected from:', addr
thread.start_new_thread(handler, (clientsock, addr))

Web service server

Our second server implements a very simple web service returning information in JSON format. Code is adapted from this one. Starting from a fresh Linux Mint 17.3 virtual machine, here is what I did to run this server:

  • using Synaptic package manager, install python-pip and python-virtualenv
  • install Flask:
virtualenv flask
flask/bin/pip install flask
  • create app.py file with following contents:
#!flask/bin/python
from flask import Flask, jsonify, abort, make_response

app = Flask(__name__)

users = [
{
'id': 1,
'name': 'Rocky',
'age': 38
},
{
'id': 2,
'name': 'Steve',
'age': 50
},
{
'id': 3,
'name': 'Melinda',
'age': 38
}
]

@app.route('/users', methods=['GET'])
def get_users():
return jsonify({'users': users})

@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = [user for user in users if user['id'] == user_id]
if len(user) == 0:
abort(404)
return jsonify({'user': user[0]})

@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == '__main__':
app.run(debug=True)
  • run the file:
chmod u+x app.py
./app.py