private Task<bool> DoHandshake(Rfc6455Handshake handshake)
        {

            return new Task<bool>(() =>
            {
                var cts = new CancellationTokenSource();
                var token = cts.Token;

                var working = true;

                var buffer = new byte[1024];
                Socket.Send(Encoding.UTF8.GetBytes(handshake.ToString()), () => Socket.Receive(buffer, r =>
                {
                    Receive();
                    IsHandshakeDone = true;

                    foreach (var ctrl in this.Controllers.GetAll())
                    {
                        ctrl.BindUnboundSubscriptions();
                    }
                    working = false;
                }, err => FireOnDisconnected()),
                            err => FireOnDisconnected());


                while (working)
                {
                    if (token.IsCancellationRequested)
                        return false;
                    Thread.Sleep(1);
                }
                return true;
            });


        }
        public void Open()
        {
            if (this.IsConnected) return;


            var connectionstring = GetConnectionstring();

            var handshake = new Rfc6455Handshake(connectionstring, _origin, this);

            SetRemoteEndpoint();

            ConnectSocket();

            var r = DoSynchronHandshake(handshake).Result;

            if (r)
                this.Connected();
            else
                throw new Exception("Could not connect to server");

        }
 private Task<bool> DoSynchronHandshake(Rfc6455Handshake handshake)
 {
     var waiter = DoHandshake(handshake);
     waiter.Start();
     return waiter;
 }
        private Task<bool> DoHandshake(Rfc6455Handshake handshake)
        {
            return new Task<bool>(() =>
            {
                Socket.Send(Encoding.UTF8.GetBytes(handshake.ToString()), () =>
                {
                    StartReceiving();
                }
                , exception =>
                {

                });

                return SpinWait.SpinUntil(() => IsHandshakeDone, 3000);
            });
        }