Commit febacbf9 authored by Tony's avatar Tony
Browse files

Update .settimeout

parent 449eeea1
File added
......@@ -37,44 +37,81 @@ market = db.market
PORT = 8000
IP = "100.100.101.16"
sendAccept = True
accept = True
#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()
createOK = False
while (not createOK):
try:
createOK = True
print('Creating socket')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
createOK = False
print ('Failed to create socket')
print ('Socket Created')
sock.settimeout(3)
host = '167.205.32.46';
sock.connect((host , 8000))
host = '167.205.32.46'
message = {"method": "join", "ip": IP, "port": PORT}
try :
#Set the whole string
sock.sendall(bytes(json.dumps(message), 'UTF-8'))
response = sock.recv(4096)
#Connecting to tracker
connectOK = False
while (not connectOK):
try:
connectOK = True
print("Connecting to " + str(host) + ":8000...")
sock.connect((host , 8000))
except socket.error:
connectOK = False
print('Failed to connect')
#Sending join request
sendOK = False
while (not sendOK):
try:
sendOK = True
print("Sending join request..")
sock.sendall(bytes(json.dumps(message), 'UTF-8'))
except socket.error:
print('Failed to send')
sendOK = False
except socket.error:
#Send failed
print ('Send failed')
sys.exit()
message = {"method": "join", "ip": IP, "port": PORT}
#receiving reply
recvOK = False
while (not recvOK):
try :
#Set the whole string
recvOK = True
print("Receiving response..")
response = sock.recv(4096)
except socket.timeout:
#Send failed
print ('Send failed')
recvOK = False
except socket.error:
print("Send error")
recvOK = False
print (response.decode('UTF-8'))
#Now receive data from tracker
decoded = json.loads(response.decode('UTF-8'))
#join reply
if (decoded['status'] == "ok"):
if (decoded['status'] == "ok"): #join accepted
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'])
elif (decoded['status'] == "error"): #join failed
print ("Join error")
#Defining All Items in Inventory
......@@ -89,19 +126,10 @@ lifeElixir = 7
manaCrystal = 8
philosopherStone = 9
#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:
#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.
conn.settimeout(3)
while True:
try:
#Receiving from client
......@@ -303,52 +331,72 @@ def clientThread(conn):
reply = {"status": "error"}
else: #valid request
serverList = server.find({"$or": [{"ip": {"$ne": str(IP)}}, {"port": {"$ne": 8000}}]})
#Request all offer in another servers
for serve in serverList:
#Make socket to all server
createOK = True
try:
print("Creating socket..")
sock_serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_serv.settimeout(3)
except socket.error: #Socket fail to create
createOK = False
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()
if (createOK):
print("Socket Created")
sock_serv.settimeout(3)
res = json.loads(response.decode('UTF-8'))
print(res)
if (res['status'] == 'ok'): #sendfind ok!
#update market
if (market.count() > 0):
market.remove({"offered_item": decoded['item'], "server.ip": serve['ip'], "server.port": serve['port']})
for off in res['offers']:
market.insert({ "offer_token": off[5],
"offered_item": off[0],
"n_offered_item": off[1],
"demanded_item": off[2],
"n_demanded_item": off[3],
"availability": True,
"server": {"ip": str(serve['ip']),"port": int(serve['port'])}})
elif (res['status'] == 'error'): #sendfind error
print("Error response from server "+ str(serve['ip']) + ":" + str(serve['port']))
sock_serv.close()
connectOK = True
try:
print("Connecting to: " + str(serve['ip']) + ":" + str(serve['port']))
sock_serv.connect((serve['ip'] , serve['port']))
except socket.error: #Socket fail to connect
connectOK = False
print('Failed to connect to another server')
request = {"method": "findoffer", "item": decoded['item']}
if (connectOK):
sendOK = True
#Sending request
try :
print("Sending request..")
sock_serv.sendall(bytes(json.dumps(request), 'UTF-8'))
except socket.error: #Send Failed
print ('Send failed')
sendOK = False
if (sendOK):
receiveOK = True
#Receiving response
try:
print("Receiving response..")
response = sock_serv.recv(4096)
except socket.error:
print('Receive failed')
receiveOK = False
if (receiveOK):
res = json.loads(response.decode('UTF-8'))
print(res)
if (res['status'] == 'ok'): #sendfind ok!
#update market
if (market.count() > 0):
market.remove({"offered_item": decoded['item'], "server.ip": serve['ip'], "server.port": serve['port']})
for off in res['offers']:
market.insert({ "offer_token": off[5],
"offered_item": off[0],
"n_offered_item": off[1],
"demanded_item": off[2],
"n_demanded_item": off[3],
"availability": True,
"server": {"ip": str(serve['ip']),"port": int(serve['port'])}})
elif (res['status'] == 'error'): #sendfind error
print("Error response from server "+ str(serve['ip']) + ":" + str(serve['port']))
sock_serv.close()
offers = []
#market (another server)
......@@ -377,10 +425,14 @@ def clientThread(conn):
print("response " + str(reply))
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break;
break
#SendAccept(client)
elif (decoded['method'] == 'sendaccept'):
global sendAccept
while(not sendAccept):
print("WAITING")
sendAccept = False
userQuery = user.find_one({"_id": ObjectId(decoded['token'])})
if (userQuery == None): #Invalid Request, token mismatch
reply = {"status": "error"}
......@@ -395,38 +447,67 @@ def clientThread(conn):
if (marketOff['availability']): #offer available
if (marketOff['n_demanded_item'] <= userQuery['inventory'][marketOff['demanded_item']]): #sufficient item
#create socket
createOK = True
try:
print("Creating socket..")
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((str(marketOff['server']['ip']) , marketOff['server']['port']))
request = {"method": "accept", "offer_token": 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
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']}})
createOK = False
market.remove({'offer_token': marketOff['offer_token']})
reply = {"status": "ok"}
if (createOK):
print ('Socket Created')
sock_serv.settimeout(3)
connectOK = True
#connect socket
try:
print("Connecting to " + str(marketOff['server']['ip']) + ":" + str(marketOff['server']['port']) + "..")
sock_serv.connect((str(marketOff['server']['ip']) , marketOff['server']['port']))
except socket.error: #connect failed
print('Connect failed')
connectOK = False
if (connectOK):
#sending request
sendOK = True
request = {"method": "accept", "offer_token": decoded['offer_token']}
try :
print("Sending request...")
sock_serv.sendall(bytes(json.dumps(request), 'UTF-8'))
except socket.error: #send failed
print ('Send failed')
sendOK = False
if (sendOK):
#recv response
recvOK = True
try:
print('Receiving Response...')
response = sock_serv.recv(4096)
except socket.error: #recv failed
print("Receiving failed")
recvOK = False
if (recvOK):
#closing socket
sock_serv.close()
#Update database
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']})
reply = {"status": "ok"}
else:
reply = {"status": "error"}
else:
reply = {"status": "error"}
else:
reply = {"status": "error"}
else:
reply = {"status": "error"}
else: #insufficient item
reply = {"status": "fail", "description": "you have insufficient item"}
else: #offer not available / already taken
......@@ -447,9 +528,14 @@ def clientThread(conn):
reply = {"status": "fail", "description": "offer is already taken"}
else: #offer already taken
reply = {"status": "fail", "description": "offer is already taken"}
sendAccept = True
#Accept(server)
elif (decoded['method'] == 'accept'):
global accept
while(not accept):
print("WAITING")
accept = False
off = offer.find_one({"offer_token": decoded['offer_token']})
if (offer == None) : #offer token not found
reply = {"status": "fail", "description": "offer not found"}
......@@ -461,10 +547,11 @@ def clientThread(conn):
reply = {"status": "ok"}
else: #offer already taken
reply = {"status": "fail", "description": "offer is already taken"}
print("response: " + str(reply))
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
break;
accept = True
break
#FetchItem(client)
elif (decoded['method'] == 'fetchitem'):
......@@ -551,7 +638,6 @@ if __name__ == '__main__':
sock.bind((IP, PORT))
except (socket.error):
print ('Bind failed')
sys.exit()
print ('Socket bind complete')
......
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