using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace CsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            String HOST = "localhost";
            int PORT = 8992;

            try
            {
                TcpClient tcpclnt = new TcpClient();

                Console.WriteLine("Connecting to " + HOST + ":" + PORT);

                tcpclnt.Connect(HOST, PORT);
                // use the ipaddress as in the server program

                Console.WriteLine("Connected");
                String str = "{\"type\":\"SUBSCRIBE\"}";
                Stream stm = tcpclnt.GetStream();

                ASCIIEncoding asen = new ASCIIEncoding();
                byte[] ba = asen.GetBytes(str);
                Console.WriteLine("Transmitting.....");
                stm.Write(ba, 0, ba.Length);
                int open = 0;
                var sb = new StringBuilder();
                //String return_data = "";
                while (true)
                {
                    byte[] bb = new byte[1];
                    int k = stm.Read(bb, 0, 1);

                    sb.Append(Convert.ToChar(bb[0]));

                    if (Convert.ToChar(bb[0]).Equals('{'))
                        open++;

                    if (Convert.ToChar(bb[0]).Equals('}'))
                        open--;

                    if (open == 0)
                    {
                        processMessage(sb.ToString());
                        sb = new StringBuilder();
                    }

                }

            }

            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }

        }

        static void processMessage(string msg)
        {
            Console.WriteLine(msg);
            //Process the feed messages here
        }
    }
}
