Commit 173dcd4b authored by Andrea Orlat's avatar Andrea Orlat
Browse files

very basic implementation of a TCP (socket) protocl server

parent ebbece4d
Loading
Loading
Loading
Loading
+60 −0
Original line number Diff line number Diff line
#*******************************************************************************
# PPPPPPPP
#
# "@(#) $Id$"
#
# Makefile of ........
#
# who       when      what
# --------  --------  ----------------------------------------------
# andrea  13/10/16  created
#

#
# Python stuff (public and local)
# ----------------------------
PY_SCRIPTS         = tcpProt-sim
PY_PACKAGES        = TCPGenericProtocolSimImpl


#
# list of all possible C-sources (used to create automatic dependencies)
# ------------------------------
CSOURCENAMES = \
	$(foreach exe, $(EXECUTABLES) $(EXECUTABLES_L), $($(exe)_OBJECTS)) \
	$(foreach rtos, $(RTAI_MODULES) , $($(rtos)_OBJECTS)) \
	$(foreach lib, $(LIBRARIES) $(LIBRARIES_L), $($(lib)_OBJECTS))

#
#>>>>> END OF standard rules

#
# INCLUDE STANDARDS
# -----------------

MAKEDIRTMP := $(shell searchFile include/acsMakefile)
ifneq ($(MAKEDIRTMP),\#error\#)
   MAKEDIR := $(MAKEDIRTMP)/include
   include $(MAKEDIR)/acsMakefile
endif

#
# TARGETS
# -------
all:	do_all
	@echo " . . . 'all' done" 

clean : clean_all 
	@echo " . . . clean done"

clean_dist : clean_all clean_dist_all 
	@echo " . . . clean_dist done"

man   : do_man 
	@echo " . . . man page(s) done"

install : install_all
	@echo " . . . installation done"


#___oOo___
+123 −0
Original line number Diff line number Diff line
#!/usr/bin/env python
# Author: Andrea Orlati <a.orlati@ira.inaf.it>

# **************************************************************************************************** 
# DISCOS Project                                                                                       
#                                                                                                      
# This code is under GNU General Public License (GPL).             
# Who                                when            What                          
# Andrea Orlati(aorlati@ira.inaf.it) 13/10/2016     Creation                                       

"""
This module provides a dummy server  a dummy server. 

How To Use This Module
======================
(See the individual classes, methods, and attributes for details)

1. Import it: ``import TCPServer``

2. Create a BoardServer object::

       rs = TCPServer(cmd, answ, defAnsw)

3. Run the server::

       rs.run()

An alternative way is to execute directly this module from a shell::

       ./TCPserver.py

To stop the server::

       rs.stop()
"""

import socket, traceback, os, sys
import binhex
from multiprocessing import Value

stop_server = Value('i', False)

class TCPServer:
   
	def __init__(self, cmd, answ, defAnsw):
		"""
		Initialize

   	Parameters:
		
		- `cmd`: a strings or commands that the server recognizes
		- 'answ': server answers to the defined commands
		- 'defAnsw': a string sent as answer to the clinet in case the command is not recognized
		- `port`: the port the server is listening for connections.
		"""

		self.host = socket.gethostbyname(socket.gethostname())
		self.port = 15001
		self.command=cmd
		self.answer=answ
		self.defaultAnswer=defAnsw
		self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

	def run(self):
		self.s.bind((self.host, self.port))
		self.s.listen(1)
		
		print "*"*40
		print "TCPServer - Waiting for connections from %s port %d..." % (self.host,self.port)
		print "Valid commands are: %s" % (self.command)
		print "*"*40
		error=False
		try:
			connection, clientaddr = self.s.accept()
			print "Got connection from %s port %d" % (connection.getpeername())
		except KeyboardInterrupt:
			raise			
		except:
			error=True
		finally:
			self.s.close()
	
		if error:
			sys.exit(0)

		try:
			while True:
				if stop_server.value:
					break
				data = connection.recv(1024)
				if '#stop' in data:
					stop_server.value = True
					connection.close()
					break
				if(data):
					answer=self.defaultAnswer
					if len(data)> 1:
						strcmp=data.strip()
						print "Received: %s" % (strcmp)
						if strcmp in self.command:
							index=self.command.index(strcmp)
							answer=self.answer[index]
					print "Sending message: %s" % (answer)
					connection.send(answer)			
		except KeyboardInterrupt:
			raise
		except:
			pass
		finally:
			connection.close()

		print "Exiting...."
		sys.exit(0)

	@staticmethod
	def stop():
		print "shutdown by external command..."
		stop_server.value = True

if __name__ == "__main__":
	bs = TCPServer()
	bs.run()
+36 −0
Original line number Diff line number Diff line
#!/usr/bin/env python
import argparse
import signal
import sys
import os
from TCPGenericProtocolSimImpl.TCPServer import TCPServer

parser = argparse.ArgumentParser(description="Start/Stop the TCP server")
parser.add_argument('action', choices=['start', 'stop'])
parser.add_argument('--cmd', action='append',dest='commands',default=[],help='Add repeated commands')
parser.add_argument('--ans', action='append',dest='answers',default=[],help='Add repeated answers')
parser.add_argument('--def', dest='defVal',default='',help='default answer')


args = parser.parse_args()

def handle_signal(num, trace):
	TCPServer.stop()

if __name__ == "__main__":


	if args.action == 'start':
		signal.signal(signal.SIGINT,handle_signal)     
		signal.signal(signal.SIGUSR1,handle_signal) 
		server = TCPServer(args.commands,args.answers,args.defVal)
		server.run()
        
	elif args.action == 'stop':
		for line in os.popen("ps ax | grep " + sys.argv[0] + " | grep -v grep"):
			fields = line.split()
			pid = fields[0]
			if int(pid) != os.getpid():
				os.kill(int(pid), signal.SIGINT)