Skip to content

Instantly share code, notes, and snippets.

@alekratz
Last active August 29, 2015 14:21
Show Gist options
  • Save alekratz/59d6e07cf110cb0cd178 to your computer and use it in GitHub Desktop.
Save alekratz/59d6e07cf110cb0cd178 to your computer and use it in GitHub Desktop.
python thin client
#!/usr/bin/python2
"""
author: Alek Ratzloff
Client that connects to the server and sends it commands.
"""
from socket import *
PORT = 65000
class Client:
def __init__(self, port):
self.port = port
self.sock = None
def __del__(self):
if self.sock:
print "WARNING: socket was not closed on program exit"
def connect(self):
"""
Connects to the server to send a command
"""
if self.sock: raise Error("Connection already active")
self.sock = socket()
self.sock.connect(('127.0.0.1', self.port))
def close(self):
"""
Closes a connection to the server
"""
if self.sock:
self.sock.close()
self.sock = None
def send_command(self, command):
if not self.sock: raise Error("Not connected to the server!")
self.sock.send(command)
def wait_response(self):
if not self.sock: raise Error("Not connected to the server!")
return self.sock.recv(1024) # receive up to 1024 bytes
def usage():
from sys import argv
print "usage:",argv[0],"command"
if __name__ == "__main__":
from sys import argv, exit
if len(argv) == 1:
usage()
exit(0)
argv = argv[1:]
command = ' '.join(argv)
cli = Client(PORT)
# connect to server
cli.connect()
cli.send_command(command)
response = cli.wait_response()
cli.close()
print "server says",response
#!/usr/bin/python2
"""
author: Alek Ratzloff
Server that listens for connections and accepts commands from the client.
"""
from socket import socket
PORT = 65000
LOCKFILE = "/tmp/py-thinclient.pid"
def write_message_hook(args):
# write to server.log
msg = ' '.join(args)
with open('server.log', 'a') as f:
f.write(msg + '\n')
class Server:
def __init__(self, port):
self.port = port
self.socket = None
self.running = False
self.hooks = {}
def add_hook(self, command, hook):
self.hooks[command] = hook
def start(self):
if self.running: raise Error("Server is already running")
self.running = True
self.socket = socket()
# listen on 127.0.0.1 by default
self.socket.bind(('127.0.0.1', self.port))
self.socket.listen(1)
while self.running:
conn, addr = self.socket.accept()
# read the message that the client is sending
message = conn.recv(1024)
command = message.split()[0]
if command in self.hooks:
self.hooks[command](message.split()[1:])
conn.send("OK")
else:
conn.send("command not found")
conn.close()
if __name__ == "__main__":
from sys import argv, exit
from os import fork, kill, remove
from os.path import isfile
from signal import SIGINT
serv = Server(PORT)
serv.add_hook("write_message", write_message_hook)
if len(argv) == 1:
serv.start()
elif argv[1] == '-d' or argv[1] == '--daemon':
# check if the lockfile exists
if isfile(LOCKFILE):
print "daemon is already running"
exit(0)
# fork and run
child = fork()
if child == -1:
print "failed to fork"
exit(-1)
elif child == 0:
# start the child operations
serv.start()
else:
print "started child process PID", child
# create the lockfile
with open(LOCKFILE, 'w') as fp:
fp.write(str(child))
elif argv[1] == '-s' or argv[1] == '--stop':
if not isfile(LOCKFILE):
print "daemon is not running, or the lockfile (%s) does not exist" % LOCKFILE
exit(0)
with open(LOCKFILE, 'r') as fp:
pid = int(fp.read())
# kill the PID
kill(pid, SIGINT)
# remove lockfile
remove(LOCKFILE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment