Esempio n. 1
0
        public void Connect(string hostname = "localhost", int port = 5858)
        {
            this.Dispose();

            this.messages = new Queue<string>();
            this.connection = new TcpClient(hostname, port);
            this.stream = this.connection.GetStream();

            this.readLoop = new Thread(() =>
            {
                byte[] packetBody;
                byte[] packetEndMarker = this.EncodePacket("\r\n\r\n");
                Regex packetHeaderPattern = new Regex(@"^Content-Length: (\d+)" + Encoding.Default.GetString(packetEndMarker) + "$");

                int contentLength;
                string message;

                string header = this.DecodePacket(this.stream.ReadToMarker(packetEndMarker));

                while (true)
                {
                    if (!this.stream.DataAvailable)
                    {
                        Thread.Sleep(0);
                        continue;
                    }

                    header = this.DecodePacket(this.stream.ReadToMarker(packetEndMarker));
                    contentLength = int.Parse(packetHeaderPattern.Match(header).Groups[1].Value);
                    packetBody = stream.ReadBytes(contentLength);
                    message = this.DecodePacket(packetBody);   
 
                    this.messages.Enqueue(message);
                }
            });

            this.readLoop.Start();
        }