Exemple #1
0
        /// <summary>
        /// Try to re-handshake on failure.
        /// </summary>
        protected override void OnFailure(Exception ex, IMessage[] messages)
        {
            this.Session.UpdateBayeuxClientState(oldState =>
            {
                if (null != oldState)
                {
                    IList <ClientTransport> transports = this.Session.NegotiateAllowedTransports();
                    if (null == transports || transports.Count == 0)
                    {
                        return(new DisconnectedState(this.Session, oldState.Transport));
                    }
                    else
                    {
                        ClientTransport newTransport = transports[0];
                        if (newTransport != null && !newTransport.Equals(oldState.Transport))
                        {
                            if (null != oldState.Transport)
                            {
                                oldState.Transport.Reset();
                            }
                            newTransport.Init();
                        }

                        return(new ReHandshakingState(this.Session, oldState.HandshakeFields, newTransport, oldState.NextBackOff));
                    }
                }

                return(null);
            });

            base.OnFailure(ex, messages);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="HandshakingState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>.
 /// </summary>
 public HandshakingState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     ClientTransport transport)
     : base(session, BayeuxClientStates.Handshaking, handshakeFields, null, transport, null, 0)
 {
 }
    public ClientController(IGameController controller)
    {
        _controller = controller;

        var clientProtocol = new ClientProtocol (this);
        _transport = new ClientTransport (clientProtocol);
    }
        public Task SendReceiveAsync()
        {
            var receiveTask = ServerTransport.ReceiveAsync(CancellationToken);
            var sendTask    = ClientTransport.SendAsync(Message, CancellationToken);

            return(Task.WhenAll(receiveTask, sendTask));
        }
Exemple #5
0
        public BayeuxClient(String url, IList <ClientTransport> transports)
        {
            //logger = Log.getLogger(GetType().FullName + "@" + this.GetHashCode());
            //Console.WriteLine(GetType().FullName + "@" + this.GetHashCode());

            handshakeListener  = new HandshakeTransportListener(this);
            connectListener    = new ConnectTransportListener(this);
            disconnectListener = new DisconnectTransportListener(this);
            publishListener    = new PublishTransportListener(this);

            if (transports == null || transports.Count == 0)
            {
                throw new ArgumentException("Transport cannot be null");
            }

            foreach (ClientTransport t in transports)
            {
                transportRegistry.Add(t);
            }

            foreach (String transportName in transportRegistry.KnownTransports)
            {
                ClientTransport clientTransport = transportRegistry.getTransport(transportName);
                if (clientTransport is HttpClientTransport)
                {
                    HttpClientTransport httpTransport = (HttpClientTransport)clientTransport;
                    httpTransport.setURL(url);
                    httpTransport.setCookieCollection(cookieCollection);
                }
            }

            bayeuxClientState = new DisconnectedState(this, null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BayeuxClientState"/> class
        /// with the specified <see cref="BayeuxClientStates"/> type.
        /// </summary>
        protected BayeuxClientState(
            BayeuxClient session,
            BayeuxClientStates type,
            IDictionary <string, object> handshakeFields,
            IDictionary <string, object> advice,
            ClientTransport transport,
            string clientId,
            long backOff)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (type == BayeuxClientStates.None)
            {
                throw new ArgumentOutOfRangeException("type");
            }
            if (transport == null)
            {
                throw new ArgumentNullException("transport");
            }

            _session = session;

            _type            = type;
            _handshakeFields = handshakeFields;
            _advice          = advice;
            _transport       = transport;
            _clientId        = clientId;
            _backOff         = backOff;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ReHandshakingState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>.
 /// </summary>
 public ReHandshakingState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     ClientTransport transport,
     long backOff)
     : base(session, BayeuxClientStates.ReHandshaking, handshakeFields, null, transport, null, backOff)
 {
 }
 public RehandshakingState(
     BayeuxClient bayeuxClient,
     IDictionary <string, object> handshakeFields,
     ClientTransport transport,
     long backoff)
     : base(bayeuxClient, State.REHANDSHAKING, handshakeFields, null, transport, null, backoff)
 {
 }
 public ConnectedState(
     BayeuxClient bayeuxClient,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId)
     : base(bayeuxClient, State.CONNECTED, handshakeFields, advice, transport, clientId, 0)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectedState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>,
 /// and the last received information from a Bayeux server like: <paramref name="advice"/>, <paramref name="clientId"/>.
 /// </summary>
 public ConnectedState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId)
     : base(session, BayeuxClientStates.Connected, handshakeFields, advice, transport, clientId, 0)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="UnconnectedState"/> class
 /// with the specified handshaking message template: <paramref name="handshakeFields"/>,
 /// and the last received information from a Bayeux server like: <paramref name="advice"/>, <paramref name="clientId"/>.
 /// </summary>
 public UnconnectedState(
     BayeuxClient session,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId,
     long backOff)
     : base(session, BayeuxClientStates.Unconnected, handshakeFields, advice, transport, clientId, backOff)
 {
 }
Exemple #12
0
 public UnconnectedState(
     BayeuxClient bayeuxClient,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId,
     long backoff)
     : base(bayeuxClient, State.UNCONNECTED, handshakeFields, advice, transport, clientId, backoff)
 {
 }
 public BayeuxClientState(BayeuxClient bayeuxClient, State type, IDictionary <string, object> handshakeFields,
                          IDictionary <string, object> advice, ClientTransport transport, string clientId, long backoff)
 {
     this.bayeuxClient    = bayeuxClient;
     this.type            = type;
     this.handshakeFields = handshakeFields;
     this.advice          = advice;
     this.transport       = transport;
     this.clientId        = clientId;
     this.backoff         = backoff;
 }
        private async Task CleanupAsync()
        {
            try
            {
                await TransportListener.StopAsync(CancellationToken);

                await Task.WhenAll(
                    ServerTransport.CloseAsync(CancellationToken),
                    ClientTransport.CloseAsync(CancellationToken));
            }
            catch {}
        }
Exemple #15
0
 protected BayeuxClientState(
     BayeuxClient bayeuxClient,
     State type,
     IDictionary <string, object> handshakeFields,
     IDictionary <string, object> advice,
     ClientTransport transport,
     string clientId,
     long backoff)
 {
     _bayeuxClient   = bayeuxClient;
     TypeValue       = type;
     HandshakeFields = handshakeFields;
     Advice          = advice;
     Transport       = transport;
     ClientId        = clientId;
     Backoff         = backoff;
 }
Exemple #16
0
        public override void handshake(IDictionary <String, Object> handshakeFields)
        {
            initialize();

            IList <String> allowedTransports = AllowedTransports;
            // Pick the first transport for the handshake, it will renegotiate if not right
            ClientTransport initialTransport = transportRegistry.getTransport(allowedTransports[0]);

            initialTransport.init();
            //Console.WriteLine("Using initial transport {0} from {1}", initialTransport.Name, Print.List(allowedTransports));

            updateBayeuxClientState(
                delegate(BayeuxClientState oldState)
            {
                return(new HandshakingState(this, handshakeFields, initialTransport));
            });
        }
        public void ConnectToServer()
        {
            if (!string.IsNullOrEmpty(this["Port"]) || !string.IsNullOrEmpty(this["IpAddress"]))
            {
                return;
            }

            var port     = int.Parse(Port);
            var endPoint = new IPEndPoint(IPAddress.Parse(IpAddress), port);

            _transport  = new ClientTransport(endPoint);
            _replicator = new Replicator.Replicator(Objects, _transport);
            _transport.ConnectionFailuer += s => ConnectionError = s;
            _transport.Connected         += () => { IsConnected = true; ConnectionError = string.Empty; };
            Objects.Clear();
            _transport.Connect();
        }
        public void UpdateHeartbeat(ClientTransport transport, KcpCon kcp, long time)
        {
            long current = time;

            if (current - m_RecvMills >= HeartbaetConstants.Timeout_Interval_Mills)
            {
                transport.Disconnect(true, true);
                return;
            }

            if (current - m_SendMills >= HeartbaetConstants.Send_Interval_Mills)
            {
                m_SendMills = current;
                ByteWriteMemory write = new ByteWriteMemory(m_RawBuffer);
                write.Write(KcpConstants.Flag_Heartbeat);
                write.Write(kcp.Conv);
                kcp.Send(m_RawBuffer, 0, 8);
            }
        }
        private async Task SetupAsync()
        {
            TransportListener = CreateTransportListener();
            await TransportListener.StartAsync(CancellationToken);

            var serverTcpTransportTask = TransportListener.AcceptTransportAsync(CancellationToken);

            ClientTransport = CreateClientTransport();
            await ClientTransport.OpenAsync(Uri, CancellationToken);

            SynchronizedClientTransport = new SynchronizedTransportDecorator(ClientTransport);

            ServerTransport = await serverTcpTransportTask;
            await ServerTransport.OpenAsync(Uri, CancellationToken);

            SynchronizedServerTransport = new SynchronizedTransportDecorator(ServerTransport);

            Message = Dummy.CreateMessage(Dummy.CreateTextContent());
        }
        public async Task TearDown()
        {
            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
            {
                if (ClientTransport != null && ClientTransport.IsConnected)
                {
                    try
                    {
                        await ClientTransport.CloseAsync(cts.Token);
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                await(TransportListener?.StopAsync(cts.Token) ?? Task.CompletedTask);
            }

            TransportListener?.DisposeIfDisposable();
            CancellationTokenSource.Dispose();

            // Setting null is required because this instance may be reused by NUnit
            TransportListener = null;
        }
 public HandshakingState(BayeuxClient bayeuxClient, IDictionary <string, object> handshakeFields, ClientTransport transport)
     : base(bayeuxClient, State.HANDSHAKING, handshakeFields, null, transport, null, 0)
 {
 }
 public AbortedState(BayeuxClient bayeuxClient, ClientTransport transport)
     : base(bayeuxClient, transport)
 {
 }
 public DisconnectedState(BayeuxClient bayeuxClient, ClientTransport transport)
     : base(bayeuxClient, State.DISCONNECTED, null, null, transport, null, 0)
 {
 }
		internal ClientResponseContext GetResponseContext( ClientTransport transport, EndPoint remoteEndPoint )
		{
			Contract.Requires( transport != null );
			Contract.Requires( remoteEndPoint != null );
			Contract.Ensures( Contract.Result<ClientResponseContext>() != null );

			var result = this.ResponseContextPool.Borrow();
			result.RenewSessionId();
			result.SetTransport( transport );
			result.RemoteEndPoint = remoteEndPoint;
			return result;
		}
Exemple #25
0
        protected void processHandshake(IMutableMessage handshake)
        {
            if (handshake.Successful)
            {
                // @@ax: I think this should be able to return a list of objects?
                Object serverTransportObject;
                handshake.TryGetValue(Message_Fields.SUPPORTED_CONNECTION_TYPES_FIELD, out serverTransportObject);
                IList <Object> serverTransports = serverTransportObject as IList <Object>;
                //Console.WriteLine("Supported transport: {0}", serverTransport);
                //IList<Object> serverTransports = new List<Object>();
                //serverTransports.Add(serverTransport);
                IList <ClientTransport> negotiatedTransports = transportRegistry.Negotiate(serverTransports, BAYEUX_VERSION);
                ClientTransport         newTransport         = negotiatedTransports.Count == 0 ? null : negotiatedTransports[0];
                if (newTransport == null)
                {
                    updateBayeuxClientState(
                        delegate(BayeuxClientState oldState)
                    {
                        return(new DisconnectedState(this, oldState.transport));
                    },
                        delegate()
                    {
                        receive(handshake);
                    });

                    // Signal the failure
                    String error = "405:c" + transportRegistry.AllowedTransports + ",s" + serverTransports.ToString() + ":no transport";

                    handshake.Successful = false;
                    handshake[Message_Fields.ERROR_FIELD] = error;
                    // TODO: also update the advice with reconnect=none for listeners ?
                }
                else
                {
                    updateBayeuxClientState(
                        delegate(BayeuxClientState oldState)
                    {
                        if (newTransport != oldState.transport)
                        {
                            oldState.transport.reset();
                            newTransport.init();
                        }

                        String action = getAdviceAction(handshake.Advice, Message_Fields.RECONNECT_RETRY_VALUE);
                        if (Message_Fields.RECONNECT_RETRY_VALUE.Equals(action))
                        {
                            return(new ConnectingState(this, oldState.handshakeFields, handshake.Advice, newTransport, handshake.ClientId));
                        }
                        else if (Message_Fields.RECONNECT_NONE_VALUE.Equals(action))
                        {
                            return(new DisconnectedState(this, oldState.transport));
                        }

                        return(null);
                    },
                        delegate()
                    {
                        receive(handshake);
                    });
                }
            }
            else
            {
                updateBayeuxClientState(
                    delegate(BayeuxClientState oldState)
                {
                    String action = getAdviceAction(handshake.Advice, Message_Fields.RECONNECT_HANDSHAKE_VALUE);
                    if (Message_Fields.RECONNECT_HANDSHAKE_VALUE.Equals(action) || Message_Fields.RECONNECT_RETRY_VALUE.Equals(action))
                    {
                        return(new RehandshakingState(this, oldState.handshakeFields, oldState.transport, oldState.nextBackoff()));
                    }
                    else if (Message_Fields.RECONNECT_NONE_VALUE.Equals(action))
                    {
                        return(new DisconnectedState(this, oldState.transport));
                    }
                    return(null);
                },
                    delegate()
                {
                    receive(handshake);
                });
            }
        }
Exemple #26
0
 protected internal override void ReleaseClientTransportAfterCall(ClientTransport transport)
 {
     transport.Dispose();
 }
        private ClientTransport GetClient(IPEndPoint client)
        {
            ClientTransport transport;
            if (!_clients.TryGetValue(client, out transport))
            {
                transport = new ClientTransport(client, _minRpc, _maxRpc, _packetDropRate);
                _clients.Add(client, transport);
            }

            return transport;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AbortedState"/> class.
 /// </summary>
 public AbortedState(BayeuxClient session, ClientTransport transport)
     : base(session, transport)
 {
 }
 public DisconnectingState(BayeuxClient bayeuxClient, ClientTransport transport, string clientId)
     : base(bayeuxClient, State.DISCONNECTING, null, null, transport, clientId, 0)
 {
 }
Exemple #30
0
 protected internal override void ReleaseClientTransportAfterCall(ClientTransport transport)
 {
    transport.Dispose();
 }
		/// <summary>
		///		Returns specified <see cref="ClientTransport"/> to the internal pool.
		/// </summary>
		/// <param name="transport">The <see cref="ClientTransport"/> to be returned.</param>
		internal abstract void ReturnTransport( ClientTransport transport );
 /// <summary>
 /// Initializes a new instance of the <see cref="DisconnectingState"/> class
 /// for the specified <paramref name="clientId"/>.
 /// </summary>
 public DisconnectingState(BayeuxClient session, ClientTransport transport, string clientId)
     : base(session, BayeuxClientStates.Disconnecting, null, null, transport, clientId, 0)
 {
 }
Exemple #33
0
        protected override void Destructor()
        {
            if (m_ReservedTransport != null)
            {
                Binding.ReleaseClientTransportAfterCall(m_ReservedTransport);
                m_ReservedTransport = null;
            }

            base.Destructor();
        }
Exemple #34
0
		/// <summary>
		///		Sets the bound <see cref="ClientTransport"/>.
		/// </summary>
		/// <param name="transport">The binding transport.</param>
		internal void SetTransport( ClientTransport transport )
		{
			Contract.Requires( transport != null );

			this.NextProcess = transport.UnpackResponseHeader;
			base.SetTransport( transport );
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="DisconnectedState"/> class.
 /// </summary>
 public DisconnectedState(BayeuxClient session, ClientTransport transport)
     : base(session, BayeuxClientStates.Disconnected, null, null, transport, null, 0)
 {
 }