Commit f60620e9 authored by Tony's avatar Tony
Browse files

Update server to server connection (not tested yet)

parent 0f76b6a5
......@@ -32,8 +32,10 @@ user = db.user
map = db.map
offer = db.offer
server = db.server
market = db.market
PORT = 8000
IP = str(socket.gethostbyname(socket.gethostname()))
#Join procedure
def join():
......@@ -47,14 +49,9 @@ def join():
print ('Socket Created')
host = '167.205.32.46';
port = 8000
sock.connect((host , port))
sock.connect((host , 8000))
ip = socket.gethostbyname(socket.gethostname())
str_ip = str(ip)
message = {"method": "join", "ip": "167.205.71.13", "port": PORT}
#message = {"method": "join", "ip": "167.205.71.13", "port": PORT}
message = {"method": "join", "ip": IP, "port": PORT}
try :
#Set the whole string
sock.sendall(bytes(json.dumps(message), 'UTF-8'))
......@@ -105,18 +102,15 @@ philosopherStone = 9
#Function for handling connections. This will be used to create threads
def clientThread(conn):
#infinite loop so that function do not terminate and thread do not end.
while True:
try:
#Receiving from client
json_input = conn.recv(4096)
if not json_input: #empty data
break
else: #data not empty
decoded = json.loads(json_input.decode('UTF-8'))
print (decoded)
print("request: " + str(decoded))
#ServerStatus(tracker)
if (decoded['method'] == "serverStatus"):
server.remove({})
......@@ -308,11 +302,65 @@ def clientThread(conn):
if (userQuery == None): #Invalid Request, token mismatch
reply = {"status": "error"}
else: #valid request
allOffer = offer.find({"user_token": {"$ne": decoded['token']}, "offered_item": decoded['item'], "availability": True})
serverList = server.find({"ip": {"$ne": IP}, "port": {"$ne": PORT}})
#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']))
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'))
if (res['status'] == 'ok'): #sendfind ok!
#update market
market.remove({"offered_item": decoded['item'], "ip": serve['ip'], "port": serve['port']})
for off in res['offers']:
market.insert({ "offer_token": res[off[5]],
"offered_item": res[off[0]],
"n_offered_item": res[off[1]],
"demanded_item": res[off[2]],
"n_demanded_item": res[off[3]],
"availability": True,
"server": {"ip": str(serve['ip']),"port": serve['port']}})
elif (res['status'] == 'error'): #sendfind error
print("Error response from server "+ str(serve['ip']) + ":" + str(serve['port']))
sock_serv.close()
offers = []
for off in allOffer:
#market (another server)
marketOffer = market.find({"offered_item": decoded['item'], "availability": True})
for off in marketOffer:
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)
#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)
reply = {"status": "ok", "offers": offers}
#FindOffer(server)
......@@ -322,9 +370,10 @@ def clientThread(conn):
for off in allOffer:
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)
reply = {"status": "ok", "offers": offers}
print(reply)
print("response " + str(reply))
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break;
......@@ -334,14 +383,57 @@ def clientThread(conn):
if (userQuery == None): #Invalid Request, token mismatch
reply = {"status": "error"}
else: #valid request
off = offer.find_one({"offer_token": decoded['offer_token']})
if (off == None): #offer token not found
reply = {"status": "fail", "description": "offer not found"}
else: #offer found
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
sock_serv.connect((marketOff['ip'] , marketOff['port']))
request = {"method": "accept", "offer_token": str(decoded['offer_token'])}
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
market.remove({'offer_token': decoded['offer_token']})
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']}})
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
if (off['availability']): #offer still available
if (off['n_demanded_item'] > userQuery['inventory'][off['demanded_item']]): #insufficient item
reply = {"status": "fail", "description": "you have insufficient item"}
else: #sufficient item. Accept OK
if (off['n_demanded_item'] <= userQuery['inventory'][off['demanded_item']]): #sufficient item
#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']}})
......@@ -350,6 +442,8 @@ def clientThread(conn):
offer.update({'offer_token': decoded['offer_token']}, {"$set": {'availability': False}})
reply = {"status": "ok"}
else: #sufficient item. Accept OK
reply = {"status": "fail", "description": "offer is already taken"}
else: #offer already taken
reply = {"status": "fail", "description": "offer is already taken"}
......@@ -367,7 +461,7 @@ def clientThread(conn):
else: #offer already taken
reply = {"status": "fail", "description": "offer is already taken"}
print(reply)
print("response: " + str(reply))
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break;
......@@ -408,7 +502,7 @@ def clientThread(conn):
else: # not available, offer already accepted (taken)
reply = {"status": "fail", "description": "Offer already accepted / taken"}
print(reply)
print("response: "+str(reply))
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
except Exception as e:
......@@ -448,16 +542,13 @@ if __name__ == '__main__':
map.insert(data)
# MAKING SOCKET CONNECTION #
#HOST = socket.gethostbyname(socket.gethostname()) # Symbolic name meaning all available interfaces
HOST = 'localhost'
#PORT = 8000 # Arbitrary non-privileged port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
#Bind socket to local host and port
try:
sock.bind((HOST, PORT))
sock.bind(('localhost', PORT))
except (socket.error):
print ('Bind failed')
sys.exit()
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment