import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This class implements java socket client
 * 
 * @author pankaj
 *
 */
public class JavaDemo {

	public static void main(String[] args)
			throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
		Socket echoSocket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		String HOST = "localhost";
		int PORT = 8992;

		try {

			System.out.println("Connecting to " + HOST + ":" + PORT);
			echoSocket = new Socket(HOST, PORT);
			out = new PrintWriter(echoSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
			System.out.println("Connected");

			String input = "{\"type\":\"SUBSCRIBE\"}";

			System.out.println("Transmitting.....");
			out.println(input);

			StringBuilder buf = new StringBuilder();
			int open = 0;

			while (input != null) {

				char[] bb = new char[1];
				in.read(bb, 0, 1);
				buf.append(bb[0]);
				if (bb[0] == '{') {
					open++;
				}
				if (bb[0] == '}') {
					open--;
				}
				if (open == 0) {
					processMessage(buf.toString());
					buf = new StringBuilder();
				}

			}

			out.close();
			in.close();
			echoSocket.close();

		} catch (UnknownHostException e) {
			System.err.println("Don't know about host:"+HOST);
			System.exit(1);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for " + "the connection to:"+HOST);
			System.exit(1);
		}

	}

	public static void processMessage(String msg) {
		System.out.println("Received msg: " + msg + "\n");
	}

}