Beispiel #1
0
        private void tReceive()
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while(true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = stream.Read(buffer, 0, 4096);
                    observer.OnNotify(new MessageWrapper(MessageType.Normal, buffer, Id));
                }
                catch
                {
                    State = ClientState.Disconnected;
                    observer.OnNotify(new MessageWrapper(MessageType.Disconnect, null, Id));
                    break;
                }

                if (bytesRead == 0)
                {
                    State = ClientState.Disconnected;
                    observer.OnNotify(new MessageWrapper(MessageType.Disconnect, null, Id));
                    break;
                }
            }
        }
Beispiel #2
0
 public void SetState(ClientState state)
 {
     _cstate = state;
     switch (state)
     {
         case ClientState.kCLIENT_STATE_LOGINSERVER_CONNECT_IN_PROGRESS:
             _state = "kCLIENT_STATE_LOGINSERVER_CONNECT_IN_PROGRESS";
             break;
         case ClientState.kCLIENT_STATE_LOGINSERVER_CONNECT_COMPLETE:
             _state = "kCLIENT_STATE_LOGINSERVER_CONNECT_COMPLETE";
             break;
         case ClientState.kCLIENT_STATE_LOGIN_IN_PROGRESS:
             _state = "kCLIENT_STATE_LOGIN_IN_PROGRESS";
             break;
         case ClientState.kCLIENT_STATE_LOGIN_SUCCESS:
             _state = "kCLIENT_STATE_LOGIN_SUCCESS";
             break;
         case ClientState.kCLIENT_STATE_CHARACTER_LIST_RECEIVED:
             _state = "kCLIENT_STATE_CHARACTER_LIST_RECEIVED";
             break;
         case ClientState.kCLIENT_STATE_WORLD_LIST_RECEIVED:
             _state = "kCLIENT_STATE_WORLD_LIST_RECEIVED";
             break;
     }
 }
Beispiel #3
0
    private void cancelJoining()
    {
        Debug.Log("Cancel joining");

        clientState=ClientState.ClientSearch;
        Network.Disconnect();
    }
Beispiel #4
0
 public ReadFileService(ClientState clientState, string semantics, int fileRegisterId)
     : base(clientState)
 {
     FileRegisterId = fileRegisterId;
     Semantics = semantics;
     ReadedFile = null;
 }
 void _presentationClient_OnChanged(object sender, ClientState e)
 {
     if (OnChanged != null)
     {
         OnChanged.Invoke(sender, e);
     }
 }
Beispiel #6
0
    private void JoinServer(HostData hostData)
    {
        Debug.Log("Joining to server: "+hostData.gameName+" | "+hostData.ip[0]+":"+hostData.port.ToString());

        clientState=ClientState.ClientJoin;
        Network.Connect(hostData);
    }
Beispiel #7
0
 public CreateFileService(ClientState clientState, string filename, int numberOfDataServers, int readQuorum, int writeQuorum)
     : base(clientState)
 {
     FileName = filename;
     NumberOfDataServers = numberOfDataServers;
     ReadQuorum = readQuorum;
     WriteQuorum = writeQuorum;
 }
Beispiel #8
0
 private void UpdateUserInterface(ClientState currentState)
 {
     if (currentState == ClientState.SignedIn) {
         //Listen for events of changes of the contact's information
         lyncClient.Self.Contact.ContactInformationChanged +=
             new EventHandler<ContactInformationChangedEventArgs>(SelfContact_ContactInformationChanged);
     }
 }
 public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
 {
     foreach (var item in ((IEnumerable<SyndicationItem>)encounteredItems).Reverse())
     {
         eventProcessor.Process(item);
         clientState.RecordSuccessfullyProcessed(item);
     }
     return new Terminate();
 }
Beispiel #10
0
 public ClientServant(TcpClient client)
 {
     m_id = null;
     m_state = ClientState.Initial;
     m_client = client;
     m_readingThread = new Thread(Reading);
     m_writingQueue = new Queue<Message>();
     m_writingThread = new Thread(Writing);
     m_clientIPEndPoint = client.Client.RemoteEndPoint as IPEndPoint;
 }
        public string GetContent(ClientState state)
        {
            Guid clientGuid = new Guid(state.ClientGuid);
            if (!NotificationStore.ContainsKey(clientGuid))
                return "";

            string result = new JavaScriptSerializer().Serialize(NotificationStore[clientGuid]);
            NotificationStore[clientGuid].Clear();
            return result;
        }
Beispiel #12
0
 public void Close()
 {
     try {
         CloseConnection();
         OnClosed();
         state = ClientState.Closed;
     } catch (Exception) {
         state = ClientState.Broken;
         throw;
     }
 }
Beispiel #13
0
 public void Open()
 {
     try {
         OpenConnection();
         OnOpen();
         state = ClientState.Open;
     } catch (Exception) {
         state = ClientState.Broken;
         throw;
     }
 }
        public AddIntlPortDialogBox(ClientState client)
        {
            InitializeComponent();

            foreach (var country in client.GetAllCountries())
            {
                //this.originComboBox.Items.Add(countries.Name);
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = country.Name;
                cbi.Tag = country.ID;
                this.countries.Items.Add(cbi);
            }
        }
Beispiel #15
0
        public MqttClient(string clientId, IMqttClient client)
        {
            if (clientId.Length < 1 || clientId.Length > 23)
            {
                throw new ArgumentException("Client identifier must be between 1 and 23 charascters.");
            }

            _clientState = ClientState.Disconnected;
            ClientId = clientId;
            _client = client;
            _client.OnMessageReceived += ClientOnMessageReceived;
            _client.OnNetworkDisconnected += ClientOnOnNetworkDisconnected;
            _manager = new StateMachineManager(_client);
        }
Beispiel #16
0
 public Task Connect(EndPoint endPoint)
 {
     var tcs = new TaskCompletionSource<bool>();
     _pipeline.OpenConnection(endPoint,
         ex =>
         {
             _state = ClientState.Connect;
             if (ex != null)
                 tcs.SetException(ProcessException(ex));
             else
                 tcs.SetResult(true);
         });
     return tcs.Task;
 }
 public SharpMessagingClient(string identity, IExtensionRegistry extensionRegistry)
 {
     _extensionService = new ExtensionService(extensionRegistry, DeliverMessage);
     _state = ClientState.ClientToServerHandshake1;
     _connection = new Connection.Connection(identity, _extensionService, false, _bufferManager)
     {
         ExtensionFrameReceived = OnExtensionFrame,
         MessageFrameReceived = OnMessageFrame,
         WriteCompleted = OnWriteCompleted,
         //ReceiveBufferSize = 65535
     };
     _connection.HandshakeReceived += OnServerHandshakeFrame;
     _connection.Disconnected += OnDisconnected;
     _connection.Fault += OnConnectionFault;
 }
 public bool CheckClient(ClientState state)
 {
     HttpCookie notificationClientCookie = state.CurrentContext.Request.Cookies.Get(guidCookieName);
     HttpCookie notificationClientTokenCookie = state.CurrentContext.Request.Cookies.Get(tokenCookieName);
     if (notificationClientCookie != null && !string.IsNullOrEmpty(notificationClientCookie.Value) &&
         notificationClientTokenCookie != null && !string.IsNullOrEmpty(notificationClientTokenCookie.Value))
     {
         if (string.Compare(notificationClientTokenCookie.Value, (GenerateToken(state, notificationClientCookie.Value)), true) == 0)
         {
             state.ClientGuid = notificationClientCookie.Value;
             return true;
         }
     }
     return false;
 }
        public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
        {
            var entry = feed.Items.ElementAt(entryIndex);

            if (!clientState.HaveAlreadyProcessed(entry))
            {
                encounteredItems.Add(entry);

                if (feed.Items.Count() > entryIndex + 1)
                {
                    return new NavigateEntryTask(feed, entryIndex + 1, encounteredItems);
                }
                return new NavigatePreviousArchiveTask(feed, encounteredItems);
            }

            return new ProcessItemsTask(encounteredItems);
        }
Beispiel #20
0
 public void BeginClosing()
 {
     lock (this)
     {
         switch (State)
         {
             case ClientState.Idling:
                 State = ClientState.Closing;
                 break;
             case ClientState.Working:
                 IsClosing = true;
                 break;
             case ClientState.Closing:
                 break;
             case ClientState.Closed:
                 break;
         }
     }
 }
Beispiel #21
0
        public Connection(TcpClient c, ServerHost s)
        {
            Client = c;
            Server = s;
            ClientStream = Client.GetStream();
            cancelToken = cTokenSource.Token;

            originIP = Client.Client.RemoteEndPoint.ToString();

            Client.LingerState = new LingerOption(false, 0);

            State = ClientState.CONNECTED;

            Server.Connections.Add(this);

            Helper.LogConsole("Connection", string.Format("New connection from {0}", originIP));
            Task.Run(WaitForData, cancelToken).ConfigureAwait(false);
            Task.Run(DoPostConnect);
        }
Beispiel #22
0
        private void Reset()
        {
            _state = ClientState.ReadingProlog;
            _context = null;

            if (_parser != null)
            {
                _parser.Dispose();
                _parser = null;
            }

            if (_writeStream != null)
            {
                _writeStream.Dispose();
                _writeStream = null;
            }

            if (InputStream != null)
            {
                InputStream.Dispose();
                InputStream = null;
            }

            ReadBuffer.Reset();

            Method = null;
            Protocol = null;
            Request = null;
            Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            PostParameters = new NameValueCollection();

            if (MultiPartItems != null)
            {
                foreach (var item in MultiPartItems)
                {
                    if (item.Stream != null)
                        item.Stream.Dispose();
                }

                MultiPartItems = null;
            }
        }
 public void SetClientState(string connectionId, ClientState state)
 {
     lock (_clientStates)
     {
         switch (state)
         {
             case ClientState.Disconnected:
                 if (_clientStates.ContainsKey(connectionId))
                 {
                     _clientStates.Remove(connectionId);
                 }
                 return;
             case ClientState.Opened:
             case ClientState.Connected:
                 _clientStates[connectionId] = state;
                 return;
             default:
                 throw new ArgumentException("Bad state");
         }
     }
 }
        private ClientState state; //Current state of the player

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructs a new Connect4ClientConnection object to manage the connection
        /// between the player connecting to the given server through the given socket.
        /// </summary>
        /// <param name="_socket">Socket the player is connecting through</param>
        /// <param name="_server">Server the player is connecting to</param>
        public Connect4ClientConnection(Socket _socket, Connect4Service _server)
        {
            socket = _socket;
            Name = null;
            state = ClientState.notPlaying;
            server = _server;
            outBuffer = new byte[1024];
            inBuffer = new byte[1024];
            pendingSends = "";
            incomingMessage = "";
            isSending = false;
            lastBadCommand = null;

            try
            {
                socket.BeginReceive(inBuffer, 0, inBuffer.Length, SocketFlags.None, MessageReceived, null);
            }
            catch (Exception)
            {
                DisconnectHelper();
            }
        }
    private const int BACKLOG = 5; // Outstanding connection queue max size

    #endregion Fields

    #region Methods

    public static void AcceptCallback(IAsyncResult asyncResult)
    {
        Socket servSock = (Socket) asyncResult.AsyncState;
        Socket clntSock = null;

        try {

          clntSock = servSock.EndAccept(asyncResult);

          Console.WriteLine("Thread {0} ({1}) - AcceptCallback(): handling client at {2}",
                        Thread.CurrentThread.GetHashCode(),
                        Thread.CurrentThread.ThreadState,
                        clntSock.RemoteEndPoint);

          ClientState cs = new ClientState(clntSock);

          clntSock.BeginReceive(cs.RcvBuffer, 0, cs.RcvBuffer.Length, SocketFlags.None,
                            new AsyncCallback(ReceiveCallback), cs);
         } catch (SocketException se) {
          Console.WriteLine(se.ErrorCode + ": " + se.Message);
          clntSock.Close();
         }
    }
        public AddPriceDialogBox(ClientState clientState, bool domestic)
        {
            InitializeComponent();
            var locationService = new LocationService(clientState);
            foreach (var routeNode in clientState.GetAllRouteNodes())
            {
                var cbi = new ComboBoxItem();
                if (routeNode is DistributionCentre)
                    cbi.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort && !domestic)
                    cbi.Content = routeNode.Country.Name;
                cbi.Tag = routeNode.ID;
                this.origin.Items.Add(cbi);

                var cbi2 = new ComboBoxItem();
                if (routeNode is DistributionCentre )
                    cbi2.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort && !domestic)
                    cbi2.Content = routeNode.Country.Name;
                cbi2.Tag = routeNode.ID;
                this.dest.Items.Add(cbi2);
            }
        }
        public AddRouteDialogBox(ClientState clientState)
        {
            InitializeComponent();
            //this.comboBox1.ItemsSource = clientState.GetAllRouteNodes();

            timesGrid.Columns.Add(new DataGridTextColumn { Header = "Day", Binding = new Binding("Day") });
            timesGrid.Columns.Add(new DataGridTextColumn { Header = "Hour", Binding = new Binding("Hour") });
            timesGrid.Columns.Add(new DataGridTextColumn { Header = "Minute", Binding = new Binding("Minute") });

            foreach (var routeNode in clientState.GetAllRouteNodes())
            {
                ComboBoxItem cbi = new ComboBoxItem();
                if (routeNode is DistributionCentre)
                    cbi.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort)
                    cbi.Content = routeNode.Country.Name;
                cbi.Tag = routeNode.ID;
                this.originComboBox.Items.Add(cbi);

                ComboBoxItem cbi2 = new ComboBoxItem();
                if (routeNode is DistributionCentre)
                    cbi2.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort)
                    cbi2.Content = routeNode.Country.Name;
                cbi2.Tag = routeNode.ID;
                this.destComboBox.Items.Add(cbi2);
            }

            foreach (var company in clientState.GetAllCompanies())
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = company.Name;
                cbi.Tag = company.ID;
                this.companyComboBox.Items.Add(cbi);
            }
        }
Beispiel #28
0
 public static extern void DisableClientState(ClientState state);
Beispiel #29
0
 public void SetClientState(ClientState state)
 {
     _state = state;
 }
Beispiel #30
0
 public abstract string ProcessCommand(ClientState sender, string[] commandWords);
Beispiel #31
0
 void ConnectError(string error)
 {
     m_State = ClientState.None;
     logger.error(error);
     m_Connection.OnConnectError(error);
 }
Beispiel #32
0
 public RelatieInkoopboekingenOperations(ClientState clientState)
 {
     ClientState = clientState;
 }
Beispiel #33
0
            public void Send(ClientState clientState, Message msg)
            {
                // This should never happen -- but make sure to handle it reasonably, just in case
                if (clientState == null)
                {
                    if (msg == null)
                    {
                        return;
                    }

                    this.log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), msg.TargetGrain);
                    MessagingStatisticsGroup.OnFailedSentMessage(msg);
                    // Message for unrecognized client -- reject it
                    if (msg.Direction == Message.Directions.Request)
                    {
                        MessagingStatisticsGroup.OnRejectedMessage(msg);
                        Message error = this.messageFactory.CreateRejectionResponse(
                            msg,
                            Message.RejectionTypes.Unrecoverable,
                            "Unknown client " + msg.TargetGrain);
                        messageCenter.SendMessage(error);
                    }
                    else
                    {
                        MessagingStatisticsGroup.OnDroppedSentMessage(msg);
                    }
                    return;
                }

                lock (clientState.PendingToSend)
                {
                    // if disconnected - queue for later.
                    if (!clientState.IsConnected)
                    {
                        if (msg == null)
                        {
                            return;
                        }

                        if (this.log.IsEnabled(LogLevel.Trace))
                        {
                            this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain);
                        }
                        clientState.PendingToSend.Enqueue(msg);
                        return;
                    }

                    // if the queue is non empty - drain it first.
                    if (clientState.PendingToSend.Count > 0)
                    {
                        if (msg != null)
                        {
                            clientState.PendingToSend.Enqueue(msg);
                        }

                        // For now, drain in-line, although in the future this should happen in yet another asynch agent
                        Drain(clientState);
                        return;
                    }
                    // the queue was empty AND we are connected.

                    // If the request includes a message to send, send it (or enqueue it for later)
                    if (msg == null)
                    {
                        return;
                    }

                    if (!Send(msg, clientState))
                    {
                        if (this.log.IsEnabled(LogLevel.Trace))
                        {
                            this.log.Trace("Queued message {0} for client {1}", msg, msg.TargetGrain);
                        }
                        clientState.PendingToSend.Enqueue(msg);
                    }
                    else
                    {
                        if (this.log.IsEnabled(LogLevel.Trace))
                        {
                            this.log.Trace("Sent message {0} to client {1}", msg, msg.TargetGrain);
                        }
                    }
                }
            }
Beispiel #34
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="gameClient"></param>
 public State(GameClient gameClient, ClientState clientState)
 {
     this.ClientState = clientState;
     this.gameClient  = gameClient;
     this.game        = gameClient.Game;
 }
 private void Receive(ClientState clientState)
 {
     clientState.WorkSocket.BeginReceive(clientState.Buffer, 0, ClientState.BufferSize, 0, ReceiveCallBack, clientState);
 }
Beispiel #36
0
 public BankboekingenOperations(ClientState clientState) : base(clientState,
                                                                BankboekingModel.ResourceName)
 {
 }
Beispiel #37
0
 public MessageIsolator(ClientState state)
 {
     m_ClientState = state;
 }
Beispiel #38
0
        public void Connect(string addr, int port)
        {
            logger.Verb("ScreenCastControl::Connecting(...) " + addr + " " + port);
            VideoHandle = this.Handle;
            //logger.Debug("RemoteDesktopClient::Connecting(...) " + addr + " " + port);

            state = ClientState.Connecting;

            cancelled = false;
            errorCode = ErrorCode.Ok;

            this.ServerAddr = addr;
            this.ServerPort = port;

            this.ClientId = RngProvider.GetRandomNumber().ToString();

            var address = "net.tcp://" + ServerAddr + "/ScreenCaster";

            if (this.ServerPort > 0)
            {
                address = "net.tcp://" + ServerAddr + ":" + ServerPort + "/ScreenCaster";
            }

            //Console.WriteLine(address);

            UpdateControls();
            var clientRect = this.ClientRectangle;

            mainTask = Task.Run(() =>
            {
                uint tryCount = 0;

                bool forceReconnect = (MaxTryConnectCount == uint.MaxValue);

                while ((forceReconnect || tryCount <= MaxTryConnectCount) && !cancelled)
                {
                    logger.Verb("ScreenCastControl::Connecting count: " + tryCount);

                    //logger.Debug("Connecting count: " + tryCount);
                    //errorMessage = "";
                    errorCode = ErrorCode.Ok;

                    try
                    {
                        var uri = new Uri(address);

                        NetTcpSecurity security = new NetTcpSecurity
                        {
                            Mode = SecurityMode.None,
                        };

                        var binding = new NetTcpBinding
                        {
                            ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10),
                            SendTimeout    = TimeSpan.FromSeconds(5),
                            OpenTimeout    = TimeSpan.FromSeconds(5),

                            Security = security,
                        };

                        factory         = new ChannelFactory <IScreenCastService>(binding, new EndpointAddress(uri));
                        factory.Closed += Factory_Closed;

                        var channel = factory.CreateChannel();

                        try
                        {
                            var channelInfos = channel.GetChannelInfos();

                            state = ClientState.Connected;
                            UpdateControls();
                            Connected?.Invoke();

                            if (channelInfos == null)
                            {
                                errorCode = ErrorCode.NotReady;
                                throw new Exception("Server not configured");
                            }

                            var videoChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is VideoChannelInfo);
                            if (videoChannelInfo != null)
                            {
                                if (videoChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0)
                                {
                                    errorCode = ErrorCode.IsBusy;
                                    throw new Exception("Server is busy");
                                }
                                SetupVideo(videoChannelInfo);

                                videoRendererSink.Resize(clientRect);
                            }

                            var audioChannelInfo = channelInfos.FirstOrDefault(c => c.MediaInfo is AudioChannelInfo);
                            if (audioChannelInfo != null)
                            {
                                if (audioChannelInfo.Transport == TransportMode.Tcp && videoChannelInfo.ClientsCount > 0)
                                {
                                    errorCode = ErrorCode.IsBusy;
                                    throw new Exception("Server is busy");
                                }

                                SetupAudio(audioChannelInfo);
                            }

                            if (VideoReceiver != null)
                            {
                                VideoReceiver.Play();

                                videoRendererSink.Start();
                            }

                            if (AudioReceiver != null)
                            {
                                AudioReceiver.Play();
                            }

                            channel.PostMessage(new ServerRequest {
                                Command = "Ping"
                            });
                            tryCount = 0;

                            state = ClientState.Running;
                            UpdateControls();

                            while (state == ClientState.Running)
                            {
                                try
                                {
                                    channel.PostMessage(new ServerRequest {
                                        Command = "Ping"
                                    });
                                    if (videoRendererSink.ErrorCode != 0)
                                    {
                                        logger.Warn("ScreenCastControl::imageProvider.ErrorCode: " + videoRendererSink.ErrorCode);

                                        // logger.Debug("imageProvider.ErrorCode: " + videoRenderer.ErrorCode);
                                        //Process render error...
                                    }

                                    //TODO::
                                    // Receivers errors...

                                    syncEvent.WaitOne(1000);
                                }
                                catch (Exception ex)
                                {
                                    state     = ClientState.Interrupted;
                                    errorCode = ErrorCode.Interrupted;
                                }
                            }
                        }
                        finally
                        {
                            CloseChannel(channel);
                        }
                    }
                    catch (EndpointNotFoundException ex)
                    {
                        errorCode = ErrorCode.NotFound;

                        logger.Error(ex.Message);

                        //logger.Error(ex.Message);

                        //Console.WriteLine(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        //logger.Error(ex);

                        if (errorCode == ErrorCode.Ok)
                        {
                            errorCode = ErrorCode.Fail;
                        }

                        //Console.WriteLine(ex);
                    }
                    finally
                    {
                        Close();
                    }

                    if (!cancelled)
                    {
                        if (errorCode != ErrorCode.Ok)
                        {
                            UpdateControls();

                            tryCount++;

                            //var statusStr = "Attempting to connect: " + tryCount + " of " + maxTryCount;
                            var statusStr = "Attempting to connect: " + tryCount;

                            SetStatus(statusStr);
                        }
                    }
                    else
                    {
                        errorCode = ErrorCode.Cancelled;
                    }
                }

                cancelled = false;

                state = ClientState.Disconnected;
                UpdateControls();

                Disconnected?.Invoke(null);

                Console.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
            });
        }
Beispiel #39
0
 public ClientStateAddressDetector(ClientState clientState)
 {
     this.clientState = clientState;
 }
Beispiel #40
0
 private void SubscribetoPresenceIfSignedIn(ClientState state)
 {
     if (state == ClientState.SignedIn)
     {
         SelfSipAddress = _client.Self.Contact.Uri;
         _client.Self.Contact.ContactInformationChanged += Contact_ContactInformationChanged;
     }
     else
     {
         //remove event handler (i.e. from previous logins etc)
         _client.Self.Contact.ContactInformationChanged -= Contact_ContactInformationChanged;
     }
 }
Beispiel #41
0
 public AggregateAddressDetector(ClientState clientState)
 {
     this.ipHlpApiDetector    = new IpHlpApiAddressDetector();
     this.clientStateDetector = new ClientStateAddressDetector(clientState);
 }
Beispiel #42
0
 public ClientGetStateResponse(IActorRef originalRequestor, ClientState clientState, ClientGetStateRequest originalRequest) : base(originalRequestor, clientState, originalRequest)
 {
 }
 private void Send(ClientState clientState)
 {
     Console.WriteLine("Sending " + _clientId);
     byte[] buffer = Encoding.UTF8.GetBytes(string.Format("Send from Thread {0} Client id {1} Count {2}", Thread.CurrentThread.ManagedThreadId, _clientId, clientState.Count));
     clientState.WorkSocket.BeginSend(buffer, 0, buffer.Length, 0, BeginSendCallBack, clientState);
 }
Beispiel #44
0
 public ArtikelomzetgroepenOperations(ClientState clientState)
     : base(clientState, ArtikelomzetgroepModel.ResourceName)
 {
 }
Beispiel #45
0
 public Query()
 {
     ServerInfo = new ServerInfo();
     State      = ClientState.Idle;
     Server     = null;
 }
Beispiel #46
0
 public Task <Response <ArtikelomzetgroepModel[]> > GetAsync(string queryString, CancellationToken cancellationToken) => ClientState.ExecuteGetAsync <ArtikelomzetgroepModel>(ResourceName, queryString, cancellationToken);
Beispiel #47
0
 public void OnChange(ClientState state)
 {
     Console.WriteLine(state);
 }
Beispiel #48
0
        //////////////////////////
        // photon
        //////////////////////////
        private void OnStateChanged(ClientState state)
        {
            Debug.Log("photon state changed: " + state.ToString());
            ClientStateRP.Value = state;

            switch (state)
            {
            case ClientState.Uninitialized:
                break;

            case ClientState.ConnectingToMasterserver:
                RefreshNetInfo("正在连接主服务器...");
                break;

            case ClientState.ConnectedToMaster:
                RefreshNetInfo("已连接主服务器");
                break;

            case ClientState.Queued:
                break;

            case ClientState.Authenticated:
                RefreshNetInfo("已授权");
                break;

            case ClientState.JoinedLobby:
                RefreshNetInfo("已连接大厅");
                OutOfGameRoot.ExecuteDoLogin();
                break;

            case ClientState.DisconnectingFromMasterserver:
                RefreshNetInfo("正在从主服务器断开...");
                break;

            case ClientState.ConnectingToGameserver:
                RefreshNetInfo("正在连接游戏服务器...");
                break;

            case ClientState.ConnectedToGameserver:
                RefreshNetInfo("已连接游戏服务器");
                break;

            case ClientState.Joining:
                RefreshNetInfo("正在加入游戏..");
                break;

            case ClientState.Joined:
                RefreshNetInfo("已经加入游戏");
                OutOfGameRoot.ExecuteDoEnterRoom();
                Publish(new OpenCoreGame());
                break;

            case ClientState.Leaving:
                RefreshNetInfo("正在离开游戏..");
                OutOfGameRoot.ExecuteDoQuitRoom();
                Publish(new CloseCoreGame());
                break;

            case ClientState.Left:
                RefreshNetInfo("已经离开游戏");
                // 在此没有响应
                break;

            case ClientState.DisconnectingFromGameserver:
                RefreshNetInfo("正在从游戏服务器断开...");
                break;

            case ClientState.QueuedComingFromGameserver:
                break;

            case ClientState.Disconnecting:
                RefreshNetInfo("正在断开..");
                break;

            case ClientState.Disconnected:
                RefreshNetInfo("已经断开与服务器的连接");
                OutOfGameRoot.ExecuteDoDisconnect();
                Publish(new CloseCoreGame());
                break;

            case ClientState.ConnectingToNameServer:
                RefreshNetInfo("正在连接名字服务器...");
                break;

            case ClientState.ConnectedToNameServer:
                RefreshNetInfo("已连接名字服务器");
                break;

            case ClientState.Authenticating:
                RefreshNetInfo("正在授权...");
                break;

            case ClientState.DisconnectingFromNameServer:
                RefreshNetInfo("正在从名字服务器断开...");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #49
0
 private void QueueRequest(ClientState clientState, Message msg) => this.sender.Send(clientState, msg);
Beispiel #50
0
        public void Run(PaddlePosition paddlePosition)
        {
            if (paddlePosition == PaddlePosition.Left)
            {
                playerPaddle.Position =
                    new Vector2f(10 + playerPaddle.Size.X, (float)VideoMode.DesktopMode.Height / 2);
                opponentPaddle.Position = new Vector2f(VideoMode.DesktopMode.Width - 10 - opponentPaddle.Size.X,
                                                       (float)VideoMode.DesktopMode.Height / 2);
            }
            else
            {
                opponentPaddle.Position =
                    new Vector2f(10 + opponentPaddle.Size.X, (float)VideoMode.DesktopMode.Height / 2);
                playerPaddle.Position = new Vector2f(VideoMode.DesktopMode.Width - 10 - playerPaddle.Size.X,
                                                     (float)VideoMode.DesktopMode.Height / 2);
            }

            ball.RandomAngle();
            ball.Position = new Vector2f((float)VideoMode.DesktopMode.Width / 2, (float)VideoMode.DesktopMode.Height / 2);

            var initState = new InitialState
            {
                StartBallAngle      = ball.Angle,
                StartBallPosition   = ball.Position,
                StartPaddlePosition = playerPaddle.Position
            };

            connection.SendMessage(JsonConvert.SerializeObject(initState));

            var windowColor = new Color(0, 0, 0);

            app.Draw(result);
            app.Display();

            while (app.IsOpen)
            {
                app.DispatchEvents();

                app.Clear(windowColor);

                GameState gameState;
                try
                {
                    gameState = JsonConvert.DeserializeObject <GameState>(connection.ReceiveMessage());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    OnClose(app, EventArgs.Empty);
                    return;
                }
                opponentHeight.SetCursorHeight(gameState.OpponentHeight);
                ball.SetPosition(gameState.BallPosition);
                ball.Angle = gameState.BallAngle;
                ball.UpdatePosition();

                playerPaddle.UpdatePosition();
                opponentPaddle.UpdatePosition();

                result.SetText(gameState.ResultMessage);

                app.Draw(playerPaddle);
                app.Draw(opponentPaddle);
                app.Draw(ball);
                app.Draw(result);

                foreach (var border in borders)
                {
                    app.Draw(border);
                }

                app.Display();

                var clientState = new ClientState();
                CheckCollisions(clientState);
                clientState.cursorHeight    = playerPaddle.Position.Y;
                clientState.newBallPosition = ball.Position;
                clientState.pause           = pause;
                if (resetRequested)
                {
                    clientState.resetRequested = true;
                    resetRequested             = false;
                }
                try
                {
                    connection.SendMessage(JsonConvert.SerializeObject(clientState));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    OnClose(app, EventArgs.Empty);
                    return;
                }
            }
        }
Beispiel #51
0
 public Disconnect(ChatMessage reason, ClientState state)
 {
     Id     = state == ClientState.Play ? 0x1A : 0x00;
     Reason = reason;
 }
 public Task <Response <InkoopboekingModel> > UploadUblAsync(UblContentModel ublContentModel, CancellationToken cancellationToken)
 {
     return(ClientState.ExecutePostAsync <UblContentModel, InkoopboekingModel>($"{ResourceName}/ubl", ublContentModel, cancellationToken));
 }
        void ClientLoop()
        {
            int pingTimer = 0;

            Logger.Instance.Log("Client connected!");

            if (Misc.Settings.Instance.Server.MaxPlayers != 0)
            {
                if (Misc.Settings.Instance.Server.MaxPlayers < ServerMain.clients.Count)
                {
                    KickClient("Too many players");
                    return;
                }
            }

            while (_clientLoopThread.IsAlive)
            {
                try
                {
                    if (_client != null && _client.Connected)
                    {
                        clientIP = ((IPEndPoint)_client.Client.RemoteEndPoint).Address.ToString();

                        pingTimer++;
                        if (pingTimer > 180)
                        {
                            SendToClient(new ServerCommand(ServerCommandType.Ping));
                            pingTimer = 0;
                        }

                        string[] commands = ReceiveFromClient();

                        if (commands != null)
                        {
                            foreach (string data in commands)
                            {
                                ClientCommand command = JsonConvert.DeserializeObject <ClientCommand>(data);

                                Version clientVersion = new Version(command.version);

                                if (clientVersion.Major != ServerMain.serverVersion.Major || clientVersion.Minor != ServerMain.serverVersion.Minor || clientVersion.Build != ServerMain.serverVersion.Build)
                                {
                                    state = ClientState.UpdateRequired;
                                    SendToClient(new ServerCommand(ServerCommandType.UpdateRequired));
                                    DestroyClient();
                                }

                                if (state != ClientState.Playing && state != ClientState.Connected)
                                {
                                    state = ClientState.Connected;
                                }

                                switch (command.commandType)
                                {
                                case ClientCommandType.SetPlayerInfo:
                                {
                                    PlayerInfo receivedPlayerInfo =
                                        JsonConvert.DeserializeObject <PlayerInfo>(command.playerInfo);
                                    if (receivedPlayerInfo != null)
                                    {
                                        if (ServerMain.serverState == ServerState.Playing)
                                        {
                                            state = ClientState.Playing;
                                        }
                                        if (playerId == 0)
                                        {
                                            playerId = receivedPlayerInfo.playerId;
                                            if (!ServerMain.clients.Contains(this))
                                            {
                                                ServerMain.clients.Add(this);
                                                Logger.Instance.Log("New player: " + receivedPlayerInfo.playerName);
                                            }
                                        }
                                        else if (playerId != receivedPlayerInfo.playerId)
                                        {
                                            return;
                                        }

                                        if (playerName == null)
                                        {
                                            playerName = receivedPlayerInfo.playerName;
                                        }
                                        else if (playerName != receivedPlayerInfo.playerName)
                                        {
                                            return;
                                        }

                                        playerScore = receivedPlayerInfo.playerScore;

                                        playerInfo = receivedPlayerInfo;

                                        if (Misc.Settings.Instance.Access.Blacklist.Contains(receivedPlayerInfo.playerId.ToString()) || Misc.Settings.Instance.Access.Blacklist.Contains(clientIP))
                                        {
                                            KickClient();
                                            return;
                                        }

                                        if (Misc.Settings.Instance.Access.WhitelistEnabled && !Misc.Settings.Instance.Access.Whitelist.Contains(receivedPlayerInfo.playerId.ToString()) && !Misc.Settings.Instance.Access.Whitelist.Contains(clientIP))
                                        {
                                            KickClient();
                                            return;
                                        }
                                    }
                                }
                                    ;
                                    break;

                                case ClientCommandType.GetServerState:
                                {
                                    if (ServerMain.serverState != ServerState.Playing)
                                    {
                                        SendToClient(new ServerCommand(ServerCommandType.SetServerState));
                                    }
                                    else
                                    {
                                        SendToClient(new ServerCommand(
                                                         ServerCommandType.SetServerState,
                                                         _selectedSongDuration: ServerMain.availableSongs[ServerMain.currentSongIndex].duration.TotalSeconds,
                                                         _selectedSongPlayTime: ServerMain.playTime.TotalSeconds));
                                    }
                                }
                                    ;
                                    break;

                                case ClientCommandType.GetAvailableSongs:
                                {
                                    SendToClient(new ServerCommand(
                                                     ServerCommandType.DownloadSongs,
                                                     _songs: ServerMain.availableSongs.Select(x => x.levelId).ToArray()));
                                };
                                    break;

                                case ClientCommandType.VoteForSong:
                                {
                                    if (ServerMain.serverState == ServerState.Voting)
                                    {
                                        votedFor = ServerMain.availableSongs.FirstOrDefault(x => x.levelId.Substring(0, 32) == command.voteForLevelId.Substring(0, 32));
                                    }
                                };
                                    break;
                                }
                            }
                        }
                        while (sendQueue.Count != 0)
                        {
                            SendToClient(sendQueue.Dequeue());
                        }
                    }
                    else
                    {
                        if ((ServerMain.serverState == ServerState.Playing && ServerMain.playTime.TotalSeconds <= ServerMain.availableSongs[ServerMain.currentSongIndex].duration.TotalSeconds - 10f) || ServerMain.serverState != ServerState.Playing)
                        {
                            DestroyClient();
                            return;
                        }
                    }
                }catch (Exception e)
                {
                    Logger.Instance.Warning($"CLIENT EXCEPTION: {e}");
                }

                Thread.Sleep(8);
            }
        }
 public InkoopboekingenOperations(ClientState clientState) : base(clientState, InkoopboekingModel.ResourceName)
 {
 }
Beispiel #55
0
 public KostenplaatsenOperations(ClientState clientState)
     : base(clientState, KostenplaatsIdentifierModel.ResourceName)
 {
 }
Beispiel #56
0
 public Task <Response <KostenplaatsModel[]> > GetAllAsync(CancellationToken cancellationToken) => ClientState.ExecuteGetAllAsync <KostenplaatsModel>(ResourceName, cancellationToken);
Beispiel #57
0
 private void textBox1_TextChanged(object sender, EventArgs e)
 {
     if (!String.IsNullOrEmpty(this.textBox1.Text))
     {
         if (this.state == ClientState.ONLINE)
         {
             this.state = ClientState.TYPING;
             this.button1.Enabled = true;
             WappSocket.Instance.WhatsSendHandler.SendComposing(this.target);
         }
     }
     else
     {
         if (state == ClientState.TYPING)
         {
             this.state = ClientState.ONLINE;
             this.button1.Enabled = false;
             WappSocket.Instance.WhatsSendHandler.SendPaused(this.target);
         }
     }
 }
Beispiel #58
0
 private void UpsertNewClientRecoveryCommand(ClientUpsertCommand c)
 {
     // When recovering set the state of the actor
     _ActorState = c.ClientStateData;
 }
        /// <summary>
        /// Update this instance.
        /// </summary>
        /// <returns>Weether or not this instane is done updating.</returns>
        public Boolean Update() {
            if (this.client != null && this.client.Connected) {
                switch (clientState) {
                    case ClientState.HandshakeConnect:
                        if (this.client.Available > 0) {
                            Byte[] header = new Byte[4];
                            this.client.GetStream().Read(header, 0, 4);

                            var stringHeader = System.Text.ASCIIEncoding.ASCII.GetString(header);

                            if (stringHeader == "TS3C") {
                                this.clientState = ClientState.HandshakePublicKey;

                                Console.WriteLine("[Client->Update] ({0}) Accepted new client into list.",
                                                  this.client.Client.RemoteEndPoint.ToString());
                            } else {
                                Console.WriteLine("[Client->Update] ({0}) Not a license request, disconnecting.",
                                                  this.client.Client.RemoteEndPoint.ToString());
                                return true;
                            }
                        }
                        break;
                    case ClientState.HandshakePublicKey:
                        if (this.client.Available > 0) {
                            Console.WriteLine("[Client->Update] ({0}) Trying to read clients public key...",
                                              this.client.Client.RemoteEndPoint.ToString());

                            // Read Packet
                            Byte[] buffer = new Byte[this.client.Available];
                            Int32 dataLength = this.client.GetStream().Read(buffer, 0, this.client.Available);
                            try {
                                // The clients key starts at 7 bytes into the message, so we ignore the previous ones.
                                this.cngOtherKey = CngKeyConverter.Import(buffer, 7);
                                this.cngKeyMaterial = cngECC.DeriveKeyMaterial(this.cngOtherKey);

                                Console.WriteLine("[Client->Update] ({0}) Successfully read public key.",
                                                  this.client.Client.RemoteEndPoint.ToString());
                                this.clientState = ClientState.HandshakeInitiateRSA;
                            } catch (Exception e) {
                                Console.WriteLine("[Client->Update] ({0}) Failed to read public key from client:",
                                                  this.client.Client.RemoteEndPoint.ToString());
                                Console.WriteLine(e);
                                return true;
                            }
                        }

                        break;
                    case ClientState.HandshakeInitiateRSA:
                        try {
                            Console.WriteLine("[Client->Update] ({0}) Building and sending response...",
                                              this.client.Client.RemoteEndPoint.ToString());

                            // Create basic packet construct.
                            Int32 constructLength = 73;
                            Byte[] construct = new Byte[]{
								// Length of Packet
								(Byte)(constructLength & 0xFF), (Byte)((constructLength >> 8) & 0xFF), (Byte)((constructLength >> 16) & 0xFF), (Byte)((constructLength >> 24) & 0xFF),
								// Actual Packet
								0x54, 0x53, 0x33, 0x41, // TS3A (Header)
								0x04, 0x00, 0x00, 0x00, // .... (What is this?) (Packet Type?)
								// RSA Secret Key
								0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
								0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
								0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
								0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
								// Null Termination
								0x00
							};
                            Array.Copy(this.rsaSecretKey, 0, construct, 12, 64);

                            // Encrypt packet for Teamspeak.
                            Byte[] packet = new Byte[construct.Length];
                            cipher.Init(true,
                                        new ParametersWithIV(new KeyParameter(this.cngKeyMaterial),
                                                             new Byte[64],
                                                             0,
                                                             64));
                            cipher.ProcessBytes(construct, 0, 4, packet, 0);
                            //cipher.DoFinal(construct, 4, constructLength, packet, 4);
                            //Array.Copy(construct, packet, 4);
                            
                            //MainClass.PrintHEX(packet);

                            // Send packet
                            this.client.GetStream().Write(packet,
                                                          0,
                                                          packet.Length);
                            this.client.GetStream().Flush();
                            this.clientState = ClientState.ReadLicenseDataHeader;
                        } catch (Exception e) {
                            Console.WriteLine(e);
                            return true;
                        }
                        break;
                    case ClientState.ReadLicenseDataHeader:
                        if (this.client.Available > 0)
                            Console.WriteLine("[Client->Update] ({0}) Available Data: {1}.",
                                              this.client.Client.RemoteEndPoint.ToString(),
                                              this.client.Available);

                        break;
                    case ClientState.ReadLicenseData:

                    default:
                        return true;
                }
                return false;
            } else
                return true;
        }
Beispiel #60
0
        public Dalamud(DalamudStartInfo info, LoggingLevelSwitch loggingLevelSwitch)
        {
            this.StartInfo          = info;
            this.loggingLevelSwitch = loggingLevelSwitch;

            this.Configuration = DalamudConfiguration.Load(info.ConfigurationPath);

            this.baseDirectory = info.WorkingDirectory;

            this.unloadSignal = new ManualResetEvent(false);

            // Initialize the process information.
            this.targetModule = Process.GetCurrentProcess().MainModule;
            this.SigScanner   = new SigScanner(this.targetModule, true);

            // Initialize game subsystem
            this.Framework = new Framework(this.SigScanner, this);

            this.WinSock2 = new WinSockHandlers();

            NetworkHandlers = new NetworkHandlers(this, this.Configuration.OptOutMbCollection);

            this.ClientState = new ClientState(this, info, this.SigScanner);

            Task.Run(async() => {
                try {
                    var res = await AssetManager.EnsureAssets(this.baseDirectory);

                    if (!res)
                    {
                        Log.Error("One or more assets failed to download.");
                        Unload();
                        return;
                    }
                } catch (Exception e) {
                    Log.Error(e, "Error in asset task.");
                    Unload();
                    return;
                }

                this.LocalizationManager = new Localization(this.StartInfo.WorkingDirectory);
                if (!string.IsNullOrEmpty(this.Configuration.LanguageOverride))
                {
                    this.LocalizationManager.SetupWithLangCode(this.Configuration.LanguageOverride);
                }
                else
                {
                    this.LocalizationManager.SetupWithUiCulture();
                }

                PluginRepository = new PluginRepository(this, this.StartInfo.PluginDirectory, this.StartInfo.GameVersion);

                var isInterfaceLoaded = false;
                if (!bool.Parse(Environment.GetEnvironmentVariable("DALAMUD_NOT_HAVE_INTERFACE") ?? "false"))
                {
                    try
                    {
                        InterfaceManager         = new InterfaceManager(this, this.SigScanner);
                        InterfaceManager.OnDraw += BuildDalamudUi;

                        InterfaceManager.Enable();
                        isInterfaceLoaded = true;
                    }
                    catch (Exception e)
                    {
                        Log.Information(e, "Could not init interface.");
                    }
                }

                Data = new DataManager(this.StartInfo.Language);
                try {
                    await Data.Initialize(this.baseDirectory);
                } catch (Exception e) {
                    Log.Error(e, "Could not initialize DataManager.");
                    Unload();
                    return;
                }

                SeStringManager = new SeStringManager(Data);

#if DEBUG
                AntiDebug = new AntiDebug(this.SigScanner);
                AntiDebug.Enable();
#endif

                // Initialize managers. Basically handlers for the logic
                CommandManager = new CommandManager(this, info.Language);
                SetupCommands();

                ChatHandlers = new ChatHandlers(this);

                if (!bool.Parse(Environment.GetEnvironmentVariable("DALAMUD_NOT_HAVE_PLUGINS") ?? "false"))
                {
                    try
                    {
                        PluginRepository.CleanupPlugins();

                        PluginManager = new PluginManager(this, this.StartInfo.PluginDirectory, this.StartInfo.DefaultPluginDirectory);
                        PluginManager.LoadPlugins();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Plugin load failed.");
                    }
                }

                this.Framework.Enable();
                this.ClientState.Enable();

                IsReady = true;

                Troubleshooting.LogTroubleshooting(this, isInterfaceLoaded);
            });
        }