コード例 #1
0
ファイル: Client.cs プロジェクト: reparadocs/Clash
        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;
                }
            }
        }
コード例 #2
0
ファイル: LobbyClient.cs プロジェクト: harleyknd1/rAPB
 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;
     }
 }
コード例 #3
0
ファイル: NetworkManager.cs プロジェクト: Gris87/PingPong3D
    private void cancelJoining()
    {
        Debug.Log("Cancel joining");

        clientState=ClientState.ClientSearch;
        Network.Disconnect();
    }
コード例 #4
0
ファイル: ReadFileService.cs プロジェクト: hfcorreia/padi-fs
 public ReadFileService(ClientState clientState, string semantics, int fileRegisterId)
     : base(clientState)
 {
     FileRegisterId = fileRegisterId;
     Semantics = semantics;
     ReadedFile = null;
 }
コード例 #5
0
 void _presentationClient_OnChanged(object sender, ClientState e)
 {
     if (OnChanged != null)
     {
         OnChanged.Invoke(sender, e);
     }
 }
コード例 #6
0
ファイル: NetworkManager.cs プロジェクト: Gris87/PingPong3D
    private void JoinServer(HostData hostData)
    {
        Debug.Log("Joining to server: "+hostData.gameName+" | "+hostData.ip[0]+":"+hostData.port.ToString());

        clientState=ClientState.ClientJoin;
        Network.Connect(hostData);
    }
コード例 #7
0
 public CreateFileService(ClientState clientState, string filename, int numberOfDataServers, int readQuorum, int writeQuorum)
     : base(clientState)
 {
     FileName = filename;
     NumberOfDataServers = numberOfDataServers;
     ReadQuorum = readQuorum;
     WriteQuorum = writeQuorum;
 }
コード例 #8
0
ファイル: LyncRunner.cs プロジェクト: wendellinfinity/LyncHCI
 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);
     }
 }
コード例 #9
0
 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();
 }
コード例 #10
0
ファイル: ClientServant.cs プロジェクト: hoxily/Wuziqi
 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;
 }
コード例 #11
0
        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;
        }
コード例 #12
0
ファイル: PathClient.cs プロジェクト: erpframework/cloudb
 public void Close()
 {
     try {
         CloseConnection();
         OnClosed();
         state = ClientState.Closed;
     } catch (Exception) {
         state = ClientState.Broken;
         throw;
     }
 }
コード例 #13
0
ファイル: PathClient.cs プロジェクト: erpframework/cloudb
 public void Open()
 {
     try {
         OpenConnection();
         OnOpen();
         state = ClientState.Open;
     } catch (Exception) {
         state = ClientState.Broken;
         throw;
     }
 }
コード例 #14
0
        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);
            }
        }
コード例 #15
0
ファイル: MqttClient.cs プロジェクト: 4058665/MQTT
        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);
        }
コード例 #16
0
ファイル: RedisChannel.cs プロジェクト: tomeucapo/RedisBoost
 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;
 }
コード例 #17
0
 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;
 }
コード例 #18
0
 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;
 }
コード例 #19
0
        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);
        }
コード例 #20
0
ファイル: Client.cs プロジェクト: y-code/softdojo
 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;
         }
     }
 }
コード例 #21
0
ファイル: Connection.cs プロジェクト: Ephemeralis/Convergence
        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);
        }
コード例 #22
0
ファイル: HttpClient.cs プロジェクト: Cocotus/NHttp
        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;
            }
        }
コード例 #23
0
 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");
         }
     }
 }
コード例 #24
0
        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();
            }
        }
コード例 #25
0
    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();
         }
    }
コード例 #26
0
        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);
            }
        }
コード例 #27
0
        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);
            }
        }
コード例 #28
0
 public static extern void DisableClientState(ClientState state);
コード例 #29
0
ファイル: UIDataGridRecords.cs プロジェクト: AByte-L/hrswauto
 public void SetClientState(ClientState state)
 {
     _state = state;
 }
コード例 #30
0
 public abstract string ProcessCommand(ClientState sender, string[] commandWords);
コード例 #31
0
 void ConnectError(string error)
 {
     m_State = ClientState.None;
     logger.error(error);
     m_Connection.OnConnectError(error);
 }
コード例 #32
0
 public RelatieInkoopboekingenOperations(ClientState clientState)
 {
     ClientState = clientState;
 }
コード例 #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);
                        }
                    }
                }
            }
コード例 #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;
 }
コード例 #35
0
 private void Receive(ClientState clientState)
 {
     clientState.WorkSocket.BeginReceive(clientState.Buffer, 0, ClientState.BufferSize, 0, ReceiveCallBack, clientState);
 }
コード例 #36
0
 public BankboekingenOperations(ClientState clientState) : base(clientState,
                                                                BankboekingModel.ResourceName)
 {
 }
コード例 #37
0
 public MessageIsolator(ClientState state)
 {
     m_ClientState = state;
 }
コード例 #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());
            });
        }
コード例 #39
0
 public ClientStateAddressDetector(ClientState clientState)
 {
     this.clientState = clientState;
 }
コード例 #40
0
ファイル: VM.cs プロジェクト: NALSS/LyncPauseMusicOnCall
 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;
     }
 }
コード例 #41
0
 public AggregateAddressDetector(ClientState clientState)
 {
     this.ipHlpApiDetector    = new IpHlpApiAddressDetector();
     this.clientStateDetector = new ClientStateAddressDetector(clientState);
 }
コード例 #42
0
 public ClientGetStateResponse(IActorRef originalRequestor, ClientState clientState, ClientGetStateRequest originalRequest) : base(originalRequestor, clientState, originalRequest)
 {
 }
コード例 #43
0
 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);
 }
コード例 #44
0
 public ArtikelomzetgroepenOperations(ClientState clientState)
     : base(clientState, ArtikelomzetgroepModel.ResourceName)
 {
 }
コード例 #45
0
 public Query()
 {
     ServerInfo = new ServerInfo();
     State      = ClientState.Idle;
     Server     = null;
 }
コード例 #46
0
 public Task <Response <ArtikelomzetgroepModel[]> > GetAsync(string queryString, CancellationToken cancellationToken) => ClientState.ExecuteGetAsync <ArtikelomzetgroepModel>(ResourceName, queryString, cancellationToken);
コード例 #47
0
 public void OnChange(ClientState state)
 {
     Console.WriteLine(state);
 }
コード例 #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();
            }
        }
コード例 #49
0
 private void QueueRequest(ClientState clientState, Message msg) => this.sender.Send(clientState, msg);
コード例 #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;
                }
            }
        }
コード例 #51
0
ファイル: Disconnect.cs プロジェクト: ObsidianMC/Obsidian
 public Disconnect(ChatMessage reason, ClientState state)
 {
     Id     = state == ClientState.Play ? 0x1A : 0x00;
     Reason = reason;
 }
コード例 #52
0
 public Task <Response <InkoopboekingModel> > UploadUblAsync(UblContentModel ublContentModel, CancellationToken cancellationToken)
 {
     return(ClientState.ExecutePostAsync <UblContentModel, InkoopboekingModel>($"{ResourceName}/ubl", ublContentModel, cancellationToken));
 }
コード例 #53
0
        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);
            }
        }
コード例 #54
0
 public InkoopboekingenOperations(ClientState clientState) : base(clientState, InkoopboekingModel.ResourceName)
 {
 }
コード例 #55
0
 public KostenplaatsenOperations(ClientState clientState)
     : base(clientState, KostenplaatsIdentifierModel.ResourceName)
 {
 }
コード例 #56
0
 public Task <Response <KostenplaatsModel[]> > GetAllAsync(CancellationToken cancellationToken) => ClientState.ExecuteGetAllAsync <KostenplaatsModel>(ResourceName, cancellationToken);
コード例 #57
0
ファイル: ChatWindow.cs プロジェクト: JeremyManz/WinApp.NET
 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);
         }
     }
 }
コード例 #58
0
 private void UpsertNewClientRecoveryCommand(ClientUpsertCommand c)
 {
     // When recovering set the state of the actor
     _ActorState = c.ClientStateData;
 }
コード例 #59
0
        /// <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;
        }
コード例 #60
0
ファイル: Dalamud.cs プロジェクト: HazukiTUT/Dalamud
        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);
            });
        }