# Name:		SockServerDemoPy.py
# Author:	Dave Renner		dmrenne@comcast.net
# Date:		09/03/11	1245
# Rev:		10/01/12	2115
# Note:		this is a called module of 'pyDemo.py'
#
# Note:		'sockServerDemoPy.py' receives socket messages from
#			'sockClientDemoPy.py' and sends acknowledgements
# Note:		'sockServerDemoPy.py' (this) must be started from the command line
#			before the main test pyDemo.py. The only command line parm 
#			to this must be the Python version number, either '26' or '30'
#			This doesn't use pickle to get the version number, as the other
#			called modules do, since this must be started before the pickle file
#			is created.

from socket import *
from types import *
from sys import argv

DEBUG1 = 0
MY_CONNECT_LIMIT = 1
MY_STD_BLOCKSIZE = 1024
PROBABLY_UNUSED_VALUE = 50007
KEEP_LOOPING = 1
v26_input_cmd = 'raw_input'
v30_input_cmd = 'input'
input_cmd = 'input'

# ############################## BOILERPLATE ############################
myConfigFile = 'pyDemoConfig.dat'

# easier just to paste this boilerplate function into all our modules
# than to import it
def printf(arg):
    cmdText = "print "
    arg_nonSlash = arg.strip('\\')
    if PythonVers == '30':
        cmdFull = cmdText + '("' + arg_nonSlash + '")'
    else:
        cmdFull = cmdText + '"' + arg_nonSlash + '"'
    exec( cmdFull )

	
# ###################################################################	
def makGetArgs( argv ) :
	# see command-line processing below for details
	# first create an empty list 		
	cmdOptions = []
	n = 1
	while (n < len(argv)):
		if (argv[0] =='__name__'):
			if debugArg:
				print('First arg is program name: ')
				#print 'First arg is program name:',
				print('')
				print(argv)
				# print argv
		else:
			cmdOptions.append(argv[n])
			n +=1
	return cmdOptions
##########################################################################

cmdLineArgs = makGetArgs( argv )

if '-30' in cmdLineArgs:
    PythonVers = '30'
    input_cmd = v30_input_cmd
# else the default is 2.6
else:
    PythonVers = '26'
    input_cmd = v26_input_cmd

########################################################################	
myHost = ''
myPort = PROBABLY_UNUSED_VALUE           
mySocket = socket( AF_INET, SOCK_STREAM )
if PythonVers == '30':
    mySocket.setsockopt( SOL_SOCKET, SO_REUSEADDR, 1 )
else:
    mySocket.setsockopt( SOL_SOCKET, SO_REUSEADDR, 1 )
#mySocket.bind( (myHost, INADDR_ANY) )
mySocket.bind( (myHost, PROBABLY_UNUSED_VALUE) )
mySocket.listen(MY_CONNECT_LIMIT)
	
# loop until we've handled one client's msg
printf("")
printf("")
printf("We are now in 'sockServerPyDemo.py'.\
\\nWe are here because we have started this process\
\\nIN A SEPARATE COMMAND SESSION IN WINDOWS\
\\nOR AS A BACKGROUND PROCESS IN UNIX/LINUX.\
\\n\
\\nWe have, haven't we?\
\\nBecause we need this process running in the background\
\\nin order for our 'sockClientPyDemo.cli.py' module testing\
\\nto work.\
\\nRight, then.\
\\n\
\\n")

printf("We have started this background process,\
\\nwhich we'll call a 'server'. It will accept a message\
\\nfrom another process (which we will call a 'client')\
\\nand which we will soon start.\
\\n\
\\n\
\\nThis demonstrates the use of sockets to send messages\
\\nfrom one running process to another.\
\\nThis technology is the basis for most\
\\nnetworking communications; it's low-level, useful,\
\\nand very straightforward in Python,\
\\n though it nmay take a rudimentary knowledge of\
\\ndata communications.\
\\n\
\\nIn real life, this process would run indefinitely.\
\\n\
\\nOK, now we will start:")

conn, addr = mySocket.accept()
CATup = conn,addr
myConn = CATup[0]
myAddr = CATup[1]
myAddrFirst = myAddr[0]
myAddrSecond = myAddr[1]
 
if DEBUG1:
    if PythonVers == '30':
        printf( str( type(myAddrFirst) ) )
        printf(myAddrFirst)
        printf("")
addrstr = "Server connected to " + myAddrFirst
printf( str(addrstr))
printf("")

while KEEP_LOOPING:
    resp = myConn.recv(MY_STD_BLOCKSIZE)
    if not resp:
        break
    else:
        youSent = 'You sent me: ' + str(resp)
        if DEBUG1:
            if PythonVers == '30':
                printf( str(type(resp)) )
                printf("")
        printf( youSent )
        myConn.send(resp)
        KEEP_LOOPING = 0
myConn.close()
