Commit dd1c6f64 authored by Tony's avatar Tony
Browse files

Update inventory & gabungin map (udah bisa ditest di tempat client dr asisten (localhost:5005)

parent 565e7736
#Socket client example in python
### Import ###
#Socket client example in python
import socket #for sockets
import sys #for exit
import hashlib
from hashlib import md5
#md5 hash function
def md5(string):
m = hashlib.md5()
m.update(string.encode('UTF-8'))
return m.hexdigest()
#def receiverHandler(conn):
#reply = conn.recv(4096)
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print ('Failed to create socket')
sys.exit()
print ('Socket Created')
host = '127.0.0.1';
host = 'localhost';
port = 5005;
try:
remote_ip = socket.gethostbyname( host )
#try:
#remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#except socket.gaierror:
#could not resolve
print ('Hostname could not be resolved. Exiting')
sys.exit()
#print ('Hostname could not be resolved. Exiting')
#sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
sock.connect((host , port))
print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
#print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
user_token = ''
#Send some data to remote server
user_input = input('Masukkan angka 1-15 (0 untuk keluar):')
......@@ -49,13 +49,13 @@ if user_input == '1':
elif user_input == '2':
username = input("Username: ")
password = input("Password: ")
message = '{"method": "signup", "username": "'+ username +'", "password": "'+ md5(password) +'"}'
message = '{"method": "signup", "username": "'+ username +'", "password": "'+ password +'"}'
#Login#
elif user_input == '3':
username = input("Username: ")
password = input("Password: ")
message = '{"method": "login", "username": "'+ username +'", "password": "'+ md5(password) +'"}'
message = '{"method": "login", "username": "'+ username +'", "password": "'+ password +'"}'
#response from server
user_token = '55335e89fc0a81d87f582ed8'
......@@ -91,7 +91,7 @@ elif user_input == '16':
try :
#Set the whole string
s.sendall(message.encode('utf-8'))
sock.sendall(bytes(message, 'UTF-8'))
except socket.error:
#Send failed
print ('Send failed')
......@@ -101,6 +101,6 @@ print ('Message send successfully')
print (message)
#Now receive data
reply = s.recv(4096)
reply = sock.recv(4096)
print (reply.decode('UTF-8'))
\ No newline at end of file
{
"name" : "Taman Sari",
"width" : 5,
"height" : 5,
"map" :
[
["0", "1", "2", "3","0"],
["0", "1", "2", "3","0"],
["0", "1", "2", "3","0"],
["0", "1", "2", "3","0"],
["0", "1", "2", "3","0"]
]
}
\ No newline at end of file
{
"name" : "Kebon Bibit",
"width" : 4,
"height" : 4,
"map" :
[
["0", "1", "2", "3"],
["0", "1", "2", "3"],
["0", "1", "2", "3"],
["0", "1", "2", "3"]
]
}
\ No newline at end of file
## Handling Connections
import json
import socket
### Import ###
import sys
import json
import time
import _thread
import socket
from _thread import *
import pymongo
from pymongo import MongoClient
import hashlib
from hashlib import md5
import random
from bson.objectid import ObjectId
#md5 hash function
def md5(string):
m = hashlib.md5()
m.update(string.encode('UTF-8'))
return m.hexdigest()
#Pymongo MongoDB Setup
client = MongoClient()
client = MongoClient('localhost',27017)
......@@ -30,68 +41,81 @@ tradebox = db.tradebox
#Function for handling connections. This will be used to create threads
def clientThread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n'.encode('utf-8')) #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
try:
#Receiving from client
json_input = conn.recv(1024)
json_input = conn.recv(4096)
if not json_input:
if not json_input: #no data received
break
else:
print('json_input', json_input.decode('UTF-8'))
decoded = json.loads(json_input.decode('UTF-8'))
#print ("JSON parsing example: ", decoded['method'])
userQuery = ''
userInventory = []
#Sign Up
if (decoded['method'] == "signup"):
query = user.find({"username": decoded['username'].lower()})
if (query.count() == 0): #user available
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
randomItems = [1,2,3,4]
random.shuffle(randomItems)
inventory = randomItems + [0,0,0,0,0,0]
#Inserting User Data
data = {"username": decoded['username'].lower(),
"password": decoded['password'],
"inventory": {"0": 2,"1": 2,"2": 2,"3": 2,"4": 0,"5": 0,"6": 0,"7": 0,"8": 0,"9": 0},
"password": md5(decoded['password']),
"inventory": inventory,
"position": {"x": 0, "y": 0},
"map_token" : "5533621ffc0a81d87f582edb"}
"map_token" : str(selectedMap['_id'])}
user.insert(data)
reply = {"status": "ok"}
else: #user exist
print("User already exist")
reply = {"status": "fail", "description": "username exists"}
#Login
elif (decoded['method'] == "login"):
userQuery = user.find_one({"username": decoded['username'], "password": decoded['password']})
userQuery = user.find_one({"username": decoded['username'], "password": md5(decoded['password'])})
if (userQuery == None): #username || password not match
print("LOGIN FAILED")
reply = {"status": "fail", "description": "username/password combination is not found"}
else: #username && password match
print("LOGIN OK")
timestamp = int(time.time())
reply = {"status": "ok", "token": str(userQuery['_id']), "x": userQuery['position']['x'], "y": userQuery['position']['y'], "time": timestamp}
#Inventory
elif (decoded['method'] == 'inventory'):
for (item,n) in userQuery['inventory'].values():
for i in range(0,n):
userInventory.append(item)
reply = {"status": "ok", "inventory": userInventory}
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']}
#MixItem
#elif (decoded['method'] == 'mixitem'):
elif (decoded['method'] == 'map'):
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):
reply = {"status": "error"}
else:
reply = {"status": "ok", "name": mapQuery["name"], "width": mapQuery["width"], "heigth": mapQuery["height"]}
print(reply)
conn.sendall(reply.encode('UTF-8'))
conn.sendall(bytes(json.dumps(reply), 'UTF-8'))
except Exception as e:
break
......@@ -101,34 +125,57 @@ def clientThread(conn):
### MAIN PROGRAM ###
if __name__ == '__main__':
nMap = 2
# LOAD MAP
mapQuery = list(map.find())
if (not mapQuery): # if map Database still empty
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}
# MAKING SOCKET CONNECTION #
HOST = '' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
data = {"name": mapName,
"width": mapWidth,
"height": mapHeight,
"map": mapMap
}
map.insert(data)
# MAKING SOCKET CONNECTION #
HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = 5005 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except (socket.error, msg):
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
#Bind socket to local host and port
try:
sock.bind((HOST, PORT))
except (socket.error, msg):
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print ('Socket bind complete')
print ('Socket bind complete')
#Start listening on socket , 10 connect requests
s.listen(10)
print ('Socket now listening')
#Start listening on socket , 10 connect requests
sock.listen(10)
print ('Socket now listening')
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.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,))
#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,))
s.close()
\ No newline at end of file
s.close()
\ No newline at end of file
import socket
import threading
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
response = "{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 5005
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
server.shutdown()
\ No newline at end of file
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