#! /usr/bin/python
import SocketServer
import json

gVAR = 5

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        print "Global is {}".format(gVAR)
        gVAR = gVAR+1
        print "Connected to {}".format(self.client_address)
        self.data = self.request.recv(1024).strip()
        print "Received {} -> {}".format(self.client_address, self.data)
        try:
            received_object = json.loads(self.data)
            return_object = json.dumps(received_object)
        except ValueError:
            return_object = "JSON error: {}".format(self.data)
        self.request.sendall(return_object+"\r\n")

if __name__ == "__main__":
    HOST, PORT = "localhost", 3210

    gVAR = 8

    # Create the server, binding to localhost on port 3210
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
