import socket
import sys
import json


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "localhost"
PORT = 8992

# Connect the socket to the port where the server is listening 
server_address = (HOST, PORT)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

#Check connection
print "Connection established" 

def processMessage(msg):
    print msg
    #Process the feed messages here
	#payload = json.dumps(msg);

try:   
    # Send data to server
    data = {"type":"SUBSCRIBE"}
    message = json.dumps(data)
    sock.sendall(message)
    return_data=""
  
    open = 0;
	
	
    while True:
        check_bracket = sock.recv(1)
        return_data = return_data + check_bracket
		#check for valid json format
        if check_bracket[0] == "{":
			open+=1
        if check_bracket[0]== "}":
			open-=1
        if open == 0:	
		    processMessage(return_data)
		    return_data = ""


#close the socket
finally:
    print >>sys.stderr, 'closing socket'
    sock.close()
