#!/usr/bin/python
#Imported modules
import socket, sys
#Function used to convert the string representing the list
#to be sorted, into a list of integer numbers
def list_from_string(string):
list = []
for i in range(len(string)):
if string[i] != "-":
try:
list.append(int(string[i]))
except ValueError:
print "Invalid Input"
return False
return list
#Function used to merge the partitioned lists into a single ordered one
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i = i + 1
else:
result.append(right[j])
j = j + 1
result = result + left[i:]
result = result + right[j:]
return result
#Recursive function used to split the initial list into half
#the most it can
def mergesort(list):
if len(list) == 1:
return list
else:
middle = len(list)/2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
#Try to get the port from the execution arguments
try:
port = int(sys.argv[1])
#If it is not specified then the default port is 9999
except IndexError:
port = 9999
#Try to get the number of clients from the execution arguments
try:
nclient = int(sys.argv[2])
#If it is not specified then the default number of clients is 1
except IndexError:
nclient = 1
#Create a socket, and bind it to the (IP, port) values
s = socket.socket()
s.bind(("localhost", port))
#Specify to the socket the number of clients to listen
s.listen(nclient)
clients = []
#Main loop
while True:
#Lines used when a new client connects with the server
sc, addr = s.accept()
clients.append(1)
print "Server -> Connection received from " + str(addr[0]) + ":" + str(addr[1])
#Receive 1024 bytes of data(String)
list_str = sc.recv(1024)
#Convert it into a list using the function listr_from_string
list = list_from_string(list_str)
#If the received string was "exit", the server prints which client
# disconnected
if list_str.lower() == "exit":
clients.pop()
print clients
print "Server -> Connection closed with " + str(addr[0]) + ":" + str(addr[1])
if len(clients) == 0:
break
else:
#The server prints the received list(string)
print "Server -> Received:", list_str
#If its False(when the string has invalid characters). It shows invalid output
if list == False:
print "Server -> Invalid Input"
#If the string was correct, order the list and print it sorted
else:
list = mergesort(list)
print "Server -> Sorted: ", list
#Send the string with the list or the "False" string to the client
sc.send(str(list))
print "Exit"
#Close the sockets
sc.close()
s.close()