-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.py
More file actions
99 lines (75 loc) · 2.21 KB
/
Server.py
File metadata and controls
99 lines (75 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# import the socket library
import socket
import json, pickle
import os, sys
#merge sort
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
return arr
# next create a socket object
s = socket.socket()
count =0
print "Socket successfully created"
# take port number as input
port = int(sys.argv[1])
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print "socket binded to %s" %(port)
# put the socket into listening mode
s.listen(5)
print "socket is listening...."
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = s.accept()
print 'Got connection from', addr
count= count+1
pid=os.fork()
if (pid)==0:
print "New child created for client request with number ", count
s.close()
while True:
data = c.recv(4096)
recievedArray = data.strip('[]').replace("\"","")
sortingArray = []
for item in recievedArray.split(","):
sortingArray.append(item)
#print "tobesend ", sortingArray
sorted = mergeSort(sortingArray)
if not data:
#print "no data condition"
break
c.send(json.dumps(sorted))
os. _exit(0)
pid,status = os.waitpid(0,WNOHANG)
# Close the connection with the client
c.close()