server.py 22.3 KB
Newer Older
1
### Import ###
2
import sys
3
import json
4
import time
5
import _thread
6
import socket
7
from _thread import *
8
9
import pymongo
from pymongo import MongoClient
10
11
12
import hashlib
from hashlib import md5
import random
13
import uuid
14

15
16
from bson.objectid import ObjectId

17
18
def getRandomMd5():
	return str(uuid.uuid4().hex)
19
20
21
22
23
24
25

#md5 hash function
def md5(string):
    m = hashlib.md5()
    m.update(string.encode('UTF-8'))
    return m.hexdigest() 
	
26
27
28
#Pymongo MongoDB Setup
client = MongoClient()
client = MongoClient('localhost',27017)
29

30
31
32
db = client.gamesister
user = db.user
map = db.map
Tony's avatar
Tony committed
33
offer = db.offer
34
server = db.server
35
market = db.market
36
37

PORT = 8000
38
IP = "100.100.101.16"
39
40
41
42
43
44
45
46
47
48
49
50
51

#Join procedure
def join():
	#Connect to tracker
	try:
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.settimeout(3)
	except socket.error:
		print ('Failed to create socket')
		sys.exit()		 
	print ('Socket Created')
	 
	host = '167.205.32.46';
52
	sock.connect((host , 8000))
53
	
54
	message = {"method": "join", "ip": IP, "port": PORT}
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
	try :
		#Set the whole string
		sock.sendall(bytes(json.dumps(message), 'UTF-8'))
		response = sock.recv(4096)
		
	except socket.error:
		#Send failed
		print ('Send failed')
		sys.exit()
	
	print (response.decode('UTF-8'))
	
	#Now receive data from tracker
	decoded = json.loads(response.decode('UTF-8'))
	
	#join reply
	if (decoded['status'] == "ok"):
		server.remove({})
		print(server.find().count())
		for serv in decoded['value']:
			server.insert({"ip": str(serv['ip']), "port": str(serv['port'])}) #Insert to database
	elif (decoded['status'] == "error"):
		print (decoded['description'])

79

Tony's avatar
Tony committed
80
81
82
83
84
85
86
87
88
89
90
91
#Defining All Items in Inventory
honey = 0
herbs = 1
clay = 2
mineral = 3
potion = 4
incense = 5
gems = 6
lifeElixir = 7
manaCrystal = 8
philosopherStone = 9

92
93
94
95
96
97
98
99
100
#Function for handling tracker connection.
#def trackerThread(conn):
	#while True:
		#try:
			#Receiving from tracker
			#json_input = conn.recv(1024)
			#if not json_input:
			#	break;
			#else:
101
102

#Function for handling connections. This will be used to create threads
103
def clientThread(conn):
104
105
106
107
	#infinite loop so that function do not terminate and thread do not end.
	while True:
		try:
			#Receiving from client
108
			json_input  = conn.recv(4096)
109
			if not json_input: #empty data
110
				break
111
			else: #data not empty
112
				decoded = json.loads(json_input.decode('UTF-8'))
113
				print("request: " + str(decoded))
114
				#ServerStatus(tracker)
115
116
117
118
119
120
121
122
				if (decoded['method'] == "serverStatus"): 	
					server.remove({})
					for serv in decoded['server']:
						server.insert({"ip": str(serv['ip']), "port": str(serv['port'])}) #Insert to database
					reply = {"status": "ok"}
					
					conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
					break
123
				
124
				#Signup(client)
125
				elif (decoded['method'] == "signup"): 
126
127
128
129
130
131
132
133
134
135
					userQuery = user.find_one({"username": decoded['username'].lower()})
					if (userQuery == None): #user available
						#Assign Map for new user
						mapQuery = list(map.find())
						randomMap = random.randrange(nMap)
						for i in range(0,nMap):
							if (i == randomMap):
								selectedMap = mapQuery[i]
						
						#Randoming items
Tony's avatar
Tony committed
136
						randomItems = [2,4,8,12]
137
138
139
140
						random.shuffle(randomItems)
						inventory = randomItems + [0,0,0,0,0,0]
						
						#Inserting User Data
141
						data = {"username": decoded['username'].lower(),
142
143
								"password": md5(decoded['password']),
								"inventory": inventory,
144
								"position": {"x": 0, "y": 0},
Tony's avatar
Tony committed
145
								"map_token" : str(selectedMap['_id']),
Tony's avatar
Tony committed
146
147
								"time": int(0),
								"collected": True}
148
149
150
151
152
153
						
						user.insert(data)
						reply = {"status": "ok"}
					else: #user exist
						reply = {"status": "fail", "description": "username exists"}
					
154
				#Login(client)
155
				elif (decoded['method'] == "login"):
Tony's avatar
Tony committed
156
157
158
159
160
161
162
163
164
					userQuery = user.find_one({"username": decoded['username'].lower()})
					if (userQuery == None): #username not exist
						reply = {"status": "fail","description": "username doesn't exist, please register first"}
					else: #username exist
						if (userQuery['password'] == md5(decoded['password'])): #password match
							reply = {"status": "ok", "token": str(userQuery['_id']), "x": userQuery['position']['x'], "y": userQuery['position']['y'], "time": userQuery['time']}
						else: #password not match
							reply = {"status": "fail", "description": "username/password combination is not found"}
							
165
				#Inventory(client)
166
				elif (decoded['method'] == 'inventory'):
167
168
169
170
171
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
						reply = {"status": "ok", "inventory": userQuery['inventory']}
172
				
173
				#MixItem(client)
Tony's avatar
Tony committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
				elif (decoded['method'] == 'mixitem'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
						if (userQuery['inventory'][decoded['item1']] >= 3 and userQuery['inventory'][decoded['item2']] >= 3): #number of item sufficient
							if ((decoded['item1'] == honey and decoded['item2'] == herbs) or (decoded['item2'] == honey and decoded['item1'] == herbs)): #into potion
								user.update({"_id":userQuery['_id']},{"$inc":{"inventory."+str(decoded['item1']):-3 , "inventory."+str(decoded['item2']):-3 , "inventory.4" : 1}})
								mixItem = potion
							elif ((decoded['item1'] == clay and decoded['item2'] == herbs) or (decoded['item2'] == clay and decoded['item1'] == herbs)): #into incense
								user.update({"_id":userQuery['_id']},{"$inc":{"inventory."+str(decoded['item1']):-3 , "inventory."+str(decoded['item2']):-3 , "inventory.5" : 1}})
								mixItem = incense
							elif ((decoded['item1'] == clay and decoded['item2'] == mineral) or (decoded['item2'] == clay and decoded['item1'] == mineral)): #into gems
								user.update({"_id":userQuery['_id']},{"$inc":{"inventory."+str(decoded['item1']):-3 , "inventory."+str(decoded['item2']):-3 , "inventory.6" : 1}})
								mixItem = gems
							elif ((decoded['item1'] == potion and decoded['item2'] == incense) or (decoded['item2'] == potion and decoded['item1'] == incense)): #into lifeElixir
								user.update({"_id":userQuery['_id']},{"$inc":{"inventory."+str(decoded['item1']):-3 , "inventory."+str(decoded['item2']):-3 , "inventory.7" : 1}})
								mixItem = lifeElixir
							elif ((decoded['item1'] == gems and decoded['item2'] == incense) or (decoded['item2'] == gems and decoded['item1'] == incense)): #into manaCrystal
								user.update({"_id":userQuery['_id']},{"$inc":{"inventory."+str(decoded['item1']):-3 , "inventory."+str(decoded['item2']):-3 , "inventory.8" : 1}})
								mixItem = manaCrystal
							elif ((decoded['item1'] == lifeElixir and decoded['item2'] == manaCrystal) or (decoded['item2'] == lifeElixir and decoded['item1'] == manaCrystal)): #into philosopherStone
								user.update({"_id":userQuery['_id']},{"$inc":{"inventory."+str(decoded['item1']):-3 , "inventory."+str(decoded['item2']):-3 , "inventory.9" : 1}})
								mixItem = philosopherStone
							else:
								mixItem = ''
							
							if (mixItem):
								reply = {"status":"ok", "item": int(mixItem)}
							else:
								reply = {"status":"fail", "description": "Item Combination is not valid"}
						else:
							reply = {"status": "fail", "description": "You have not enough items to combine"}
Tony's avatar
Tony committed
207
				
208
				#Map(client)
209
210
211
212
				elif (decoded['method'] == 'map'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
Tony's avatar
Tony committed
213
					else: #valid request
214
						mapQuery = map.find_one({"_id": ObjectId(userQuery['map_token'])})
Tony's avatar
Tony committed
215
						if(mapQuery == None): #map not found
216
							reply = {"status": "error"}
Tony's avatar
Tony committed
217
						else: #map OK
Tony's avatar
Tony committed
218
							reply = {"status": "ok", "name": mapQuery["name"], "width": mapQuery["width"], "height": mapQuery["height"]}
219
				
220
				#Move(client)
Tony's avatar
Tony committed
221
222
223
224
225
226
227
228
229
230
				elif (decoded['method'] == 'move'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else:
						mapQuery = map.find_one({"_id": ObjectId(userQuery['map_token'])})
						if (mapQuery == None): #map not found
							reply = {"status": "error"}
						else: #map OK
							timeNow = int(time.time())
Tony's avatar
Tony committed
231
							if (userQuery['time'] > timeNow): # still on the way
Tony's avatar
Tony committed
232
								reply = {"status":"fail","decription": "You are still on the way"}
Tony's avatar
Tony committed
233
234
							else: # character has been arrived
								if (userQuery['position']['x'] == decoded['x'] and userQuery['position']['y'] == decoded['y']): #move to same place
Tony's avatar
Tony committed
235
236
237
									reply = {"status": "fail", "description": "You are already here"}
								else:
									if (decoded['x'] < mapQuery["width"] and decoded['x'] >= 0 and
Tony's avatar
Tony committed
238
										decoded['x'] < mapQuery["height"] and decoded['y'] >= 0): #move OK
Tony's avatar
Tony committed
239
240
										
										jarak = abs(decoded['x'] - userQuery['position']['x']) + abs(decoded['y'] - userQuery['position']['y'])
Tony's avatar
Tony committed
241
242
243
										user.update({"_id": userQuery['_id']}, {"$set": {"time": int(timeNow + 7 * jarak), "position.x": int(decoded['x']), "position.y": int(decoded['y']), "collected": False}})
										reply = {"status": "ok", "time" : int(timeNow+7 * jarak)}
									else: # out of bound target
Tony's avatar
Tony committed
244
245
										reply = {"status": "fail", "description": "Your destination is out of your reach"}
				
246
				#Field(client)
Tony's avatar
Tony committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
				elif (decoded['method'] == 'field'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
						timeNow = int(time.time())
						if (userQuery['time'] > timeNow): #still on the way
							reply = {"status":"fail","decription": "You are still on the way"}
						else:
							if (userQuery['collected']): # item already collected
								reply = {"status":"fail", "description": "Item is already collected"}
							else: #collect granted
								mapQuery = map.find_one({"_id": ObjectId(userQuery['map_token'])})
								item =  mapQuery['map'][userQuery['position']['y']][userQuery['position']['x']]
								user.update({"_id": userQuery['_id']},{"$set": {"collected": True},"$inc": {"inventory."+str(item): 1}})
								reply = {"status": "ok", "item": item}
				
264
				#Offer(client)
Tony's avatar
Tony committed
265
266
267
268
269
270
271
272
273
274
275
				elif (decoded['method'] == 'offer'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
						if (userQuery['inventory'][decoded['offered_item']] < decoded['n1']): #resource not enough
							reply = {"status": "fail", "description": "insufficient resource"}
						else:
							#update inventory
							user.update({"_id": userQuery['_id']}, {"$inc": {"inventory."+ str(decoded['offered_item']) : -decoded['n1']}})
							#insert new offer
276
277
							offer.insert({	"offer_token": getRandomMd5(),
											"user_token": str(userQuery['_id']),
Tony's avatar
Tony committed
278
279
280
281
282
283
284
											"offered_item": decoded['offered_item'],
											"n_offered_item": decoded['n1'],
											"demanded_item": decoded['demanded_item'],
											"n_demanded_item": decoded['n2'],
											"availability": True})
							reply = {"status": "ok"}
				
285
				#Tradebox(client)
Tony's avatar
Tony committed
286
287
288
289
290
291
292
293
				elif (decoded['method'] == 'tradebox'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
						allOffer = offer.find({"user_token": decoded['token']})
						offers = []
						for off in allOffer:
294
							singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
Tony's avatar
Tony committed
295
							offers.append(singleOffer)
296
						
Tony's avatar
Tony committed
297
298
						reply = {"status": "ok", "offers": offers}
				
299
300
301
302
303
304
				#SendFind(client)
				elif (decoded['method'] == 'sendfind'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
305
						serverList = server.find({"$or": [{"ip": {"$ne": str(IP)}}, {"port": {"$ne": 8000}}]})
306
307
308
309
310
311
312
313
314
315
316
						
						#Request all offer in another servers
						for serve in serverList:
							#Make socket to all server
							try:
								sock_serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
								sock_serv.settimeout(3)
							except socket.error: #Socket fail to create
								print ('Failed to create socket')
							
							sock_serv.connect((serve['ip'] , serve['port']))
Tony's avatar
Tony committed
317
							
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
							request = {"method": "findoffer", "item": decoded['item']}
							
							#Sending request
							try :
								sock_serv.sendall(bytes(json.dumps(request), 'UTF-8'))
							except socket.error: #Send Failed
								print ('Send failed')
								sys.exit()
							#Receiving response
							try:
								response = sock_serv.recv(4096)
							except socket.error:
								print('receive failed')
								sys.exit()
								
							res = json.loads(response.decode('UTF-8'))
Tony's avatar
Tony committed
334
							print(res)
335
336
							if (res['status'] == 'ok'): #sendfind ok!
								#update market
Tony's avatar
Tony committed
337
								if (market.count() > 0):
338
									market.remove({"offered_item": decoded['item'], "server.ip": serve['ip'], "server.port": serve['port']})
339
								for off in res['offers']:
Tony's avatar
Tony committed
340
341
342
343
344
									market.insert({	"offer_token": off[5],
													"offered_item": off[0],
													"n_offered_item": off[1],
													"demanded_item": off[2],
													"n_demanded_item": off[3],
345
													"availability": True,
Tony's avatar
Tony committed
346
347
													"server": {"ip": str(serve['ip']),"port": int(serve['port'])}})
													
348
349
350
351
352
							elif (res['status'] == 'error'): #sendfind error
								print("Error response from server "+ str(serve['ip']) + ":" + str(serve['port']))
							
							sock_serv.close()
						
353
						offers = []
354
355
356
						#market (another server)
						marketOffer = market.find({"offered_item": decoded['item'], "availability": True})
						for off in marketOffer:
357
							singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
358
							offers.append(singleOffer)
359
360
361
362
363
364
365
						
						#own server
						ownOffer = offer.find({"user_token": {"$ne": decoded['token']}, "offered_item": decoded['item'], "availability": True})
						for off in ownOffer:
							singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
							offers.append(singleOffer)
						
366
						reply = {"status": "ok", "offers": offers}
Tony's avatar
Tony committed
367
				
368
369
				#FindOffer(server)
				elif (decoded['method'] == 'findoffer'):
370
					allOffer = offer.find({"offered_item": decoded['item'], "availability": True})
371
372
					offers = []
					for off in allOffer:
373
						singleOffer = [int(off['offered_item']),int(off['n_offered_item']),int(off['demanded_item']),int(off['n_demanded_item']),off['availability'],str(off['offer_token'])]
374
						offers.append(singleOffer)
375
					
376
					reply = {"status": "ok", "offers": offers}
377
					
378
					print("response " + str(reply))
379
380
381
382
383
384
385
386
387
					conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
					break;
					
				#SendAccept(client)
				elif (decoded['method'] == 'sendaccept'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
						off = offer.find_one({"offer_token": decoded['offer_token']}) # search own server
						if (off == None): #offer token not found in own server
							marketOff = market.find_one({"offer_token": decoded['offer_token']}) #search in another server
							
							if (marketOff == None): #offer not found in another server
								reply = {"status": "fail", "description": "offer not found"}
							else: #offer found in another server
								if (marketOff['availability']): #offer available
									if (marketOff['n_demanded_item'] <= userQuery['inventory'][marketOff['demanded_item']]): #sufficient item
										#create socket
										try:
											sock_serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
											sock_serv.settimeout(3)
										except socket.error:
											print ('Failed to create socket')
											sys.exit()		 
										print ('Socket Created')
										
										#connect socket
407
										sock_serv.connect((str(marketOff['server']['ip']) , marketOff['server']['port']))
Tony's avatar
Tony committed
408
										request = {"method": "accept", "offer_token": decoded['offer_token']}
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
										try : 
											sock_serv.sendall(bytes(json.dumps(request), 'UTF-8')) 
										except socket.error: #send failed
											print ('Send failed')
											sys.exit()
										
										#recv response
										try:
											response = sock_serv.recv(4096)
										except socket.error: #recv failed
											print("Recv failed")
											sys.exit()
										
										#closing socket
										sock_serv.close()
										#Update database
425
426
427
428
										user.update({'_id': ObjectId(decoded['token'])},{"$inc": {'inventory.'+str(marketOff['demanded_item']): -marketOff['n_demanded_item'], 
																							'inventory.'+str(marketOff['offered_item']): marketOff['n_offered_item']}})
										
										market.remove({'offer_token': marketOff['offer_token']})
429
430
431
432
433
434
435
										reply = {"status": "ok"}
									else: #insufficient item
										reply = {"status": "fail", "description": "you have insufficient item"}
								else: #offer not available / already taken
									reply = {"status": "fail", "description": "offer is already taken"}
								
						else: #offer found in own server
436
							if (off['availability']): #offer still available
437
								if (off['n_demanded_item'] <= userQuery['inventory'][off['demanded_item']]): #sufficient item
438
439
440
441
442
443
444
445
									#update inventory of acceptor
									user.update({'_id': ObjectId(decoded['token'])},{"$inc": {'inventory.'+str(off['demanded_item']): -off['n_demanded_item'], 
																					'inventory.'+str(off['offered_item']): off['n_offered_item']}})
									
									#turn availability of offer to false
									offer.update({'offer_token': decoded['offer_token']}, {"$set": {'availability': False}})
									
									reply = {"status": "ok"}
446
447
								else: #sufficient item. Accept OK
									reply = {"status": "fail", "description": "offer is already taken"}
448
449
							else: #offer already taken
								reply = {"status": "fail", "description": "offer is already taken"}
450
451
					
				#Accept(server)
452
453
454
455
456
457
458
459
460
461
462
463
464
				elif (decoded['method'] == 'accept'):
					off = offer.find_one({"offer_token": decoded['offer_token']})
					if (offer == None) : #offer token not found
						reply = {"status": "fail", "description": "offer not found"}
					else: #offer found
						if (off['availability']): #offer still available
							#turn availability of offer to false
							offer.update({'offer_token': decoded['offer_token']}, {"$set": {'availability': False}})
							
							reply = {"status": "ok"}
						else: #offer already taken
							reply = {"status": "fail", "description": "offer is already taken"}
					
465
					print("response: " + str(reply))
466
467
					conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
					break;
468
469
470
471
472
473
474
				
				#FetchItem(client)
				elif (decoded['method'] == 'fetchitem'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
475
						off = offer.find_one({"offer_token": decoded['offer_token']})
476
477
478
479
480
481
482
483
484
485
						if (off == None): #offer token not found
							reply = {"status": "fail", "description": "offer not found"}
						else: #offer found
							if (off['availability']): #still available
								reply = {"status": "fail", "description": "offer still available"}
							else: #not available, ready to fetch
								#update inventory of offerer
								user.update({'_id': ObjectId(decoded['token'])},{"$inc": {'inventory.'+str(off['demanded_item']): off['n_demanded_item']}})
								
								#remove offer
486
								offer.remove({'offer_token': decoded['offer_token']})
487
488
489
								reply = {"status": "ok"}
								
				#CancelOffer(client)
Tony's avatar
Tony committed
490
491
492
493
494
				elif (decoded['method'] == 'canceloffer'):
					userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
					if (userQuery == None): #Invalid Request, token mismatch
						reply = {"status": "error"}
					else: #valid request
495
						off = offer.find_one({'offer_token': decoded['offer_token']})
Tony's avatar
Tony committed
496
497
498
499
500
						if (off == None): #Offer not found
							reply = {"status": "fail", "description": "Offer not found"}
						else: # Offer found
							if (off['availability']): #offer still available, cancel OK
								user.update({"_id": userQuery['_id']},{"$inc": {"inventory."+str(off['offered_item']): off['n_offered_item']}})
501
								offer.remove({"offer_token": off['offer_token']})
Tony's avatar
Tony committed
502
503
504
505
								reply = {"status": "ok"}
							else: # not available, offer already accepted (taken)
								reply = {"status": "fail", "description": "Offer already accepted / taken"}
							
506
				print("response: "+str(reply))
507
				
508
				conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
509
510
511
512
513
514
		except Exception as e:
			break
	
    #came out of loop
	conn.close()

515
516

### MAIN PROGRAM ###
517
518
if __name__ == '__main__':
	nMap = 2
519
520
521
522
	
	#Join
	#join()
	
523
	# LOAD MAP
Tony's avatar
Tony committed
524
	if (map.count() == 0): # if map Database still empty
525
526
527
528
529
530
531
532
533
534
535
		for i in range (0,nMap):
			mapFile = "map_" + str(i) + ".json"
			with open(mapFile) as json_file:
				json_map = json.load(json_file)
				# Ambil data dari file
				mapName = json_map['name']
				mapWidth = json_map['width']
				mapHeight = json_map['height']
				mapMap = json_map['map']
				
				reply = {"status": "ok", "name": mapName, "width": mapWidth, "height": mapHeight}
536

537
538
539
540
541
542
543
544
				data = {"name": mapName,
						"width": mapWidth,
						"height": mapHeight,
						"map": mapMap
						}				
				map.insert(data)
	
	# MAKING SOCKET CONNECTION #
545
	
546
547
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	print ('Socket created')
548
	
549
550
	#Bind socket to local host and port
	try:
551
		sock.bind((IP, PORT))
552
553
	except (socket.error):
		print ('Bind failed')
554
		sys.exit()
555

556
	print ('Socket bind complete')
557

558
559
560
	#Start listening on socket , 10 connect requests
	sock.listen(10) 
	print ('Socket now listening')
561

562
563
564
565
566
567
568
569
	#now keep talking with the client
	while True:
		#wait to accept a connection - blocking call
		conn, addr = sock.accept()
		print ('Connected with ' + addr[0] + ':' + str(addr[1]))
		
		#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
		start_new_thread(clientThread ,(conn,))
570

571
	sock.close()