Advertisement
gauravssnl

Json gateway.py

Nov 27th, 2016
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import SocketServer,threading,json
  2. conn={}
  3. conn_lock=threading.Lock()
  4.  
  5. class ThreadingServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer):
  6.     allow_reuse_address=True
  7.  
  8. class Handler(SocketServer.StreamRequestHandler):
  9.     def handle(self):
  10.         print "A new client connected",self.client_address
  11.         msg=json.read_stream(self.rfile)
  12.         if "!name" in msg:
  13.             name =msg["!name"]
  14.             wlock=threading.Lock()
  15.             conn_lock.acquire()
  16.             conn[name]=(wlock,self.wfile)
  17.             conn_lock.release()
  18.             print "Client registered (%s)"%name
  19.             reply={"ok": u"registered"}
  20.             self.wfile.write(json.write(reply))
  21.             self.wfile.flush()
  22.         else:
  23.             reply={"err" : u"Invalid name"}
  24.             self.wfile.write(json.write(reply))
  25.             return
  26.         handle_connection(self,name)
  27.                
  28.     def handle_connection(self,name):
  29.         while True:
  30.             try:
  31.                 msg=json.read_stream(self.rfile)
  32.             except:
  33.                 msg={"!close": True}
  34.             if "!close" in msg:
  35.                 print "Client  exits (%s)"%name, self.cient_address
  36.                 conn_lock.acquire()
  37.                 if name in conn:
  38.                     del conn[name]
  39.                 conn_lock.release()
  40.                 break
  41.             elif "!dst" in msg:
  42.                 wfile=None
  43.                 conn_lock.acquire()
  44.                 if msg["!dst"] in conn:
  45.                     wlock,wfile=conn[msg["!dst"]]
  46.                 conn_lock.acquire()
  47.                 if wfile:
  48.                     wlock.acquire()
  49.                     try:
  50.                         wfile.write(json.write(msg))
  51.                     finally:
  52.                         wlock.release()
  53. server=ThreadingServer((" ",8080),Handler)
  54. print "JSON gateway is running!"
  55. print "Waiting for new clients..."
  56. server.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement