Ejemplo n.º 1
0
        public ClientSession(INetworkClient client)
        {
            // set last received
            lastPacketReceive = DateTime.Now.Ticks;

            // lag mode
            _random = new Random((int)client.ClientId);

            // initialize lagging mode
            bool isLagMode = System.Configuration.ConfigurationManager.AppSettings["LagMode"].ToLower() == "true";

            // initialize network client
            _client = client;

            // absolutely new instantiated Client has no SessionId
            SessionId = 0;

            // register for NetworkClient events
            _client.MessageReceived += OnNetworkClientMessageReceived;

            // start observer for receiving packets
            _receiveQueue = new ConcurrentQueue<byte[]>();
            _receiveQueueObservable = Observable.Interval(new TimeSpan(0, 0, 0, 0, (isLagMode ? 1000 : 10)))
                .Subscribe(x => HandlePackets());
        }
Ejemplo n.º 2
0
        public bool UpdateLastInfo(IDatabase database, INetworkClient client)
        {
            var t2 = Functions.Time();

            return(false);
            //database.ExecuteNonQuery($"UPDATE characters SET last_connection={t2} WHERE character_id={Id}") == 1;
        }
Ejemplo n.º 3
0
 public GeolocalizationService(INetworkClient client,
                               IButterflyMobileClient butterflyMobileClient)
     : base()
 {
     this.butterflyMobileClient           = butterflyMobileClient;
     this.geolocalizationBackgroundWorker = new GeolocalizationBackgroundWorker(client, butterflyMobileClient);
 }
Ejemplo n.º 4
0
        protected virtual ClientSession IntializeNewSession(INetworkClient client)
        {
            ClientSession session = new ClientSession(client);

            client.SetClientSession(session);
            return(session);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Connect to specified debugger endpoint.
        /// </summary>
        /// <param name="uri">URI identifying the endpoint to connect to.</param>
        public void Connect(Uri uri)
        {
            Utilities.ArgumentNotNull("uri", uri);
            LiveLogger.WriteLine("Debugger connecting to URI: {0}", uri);

            Close();
            lock (this._networkClientLock)
            {
                var       connection_attempts = 0;
                const int MAX_ATTEMPTS        = 5;
                while (true)
                {
                    connection_attempts++;
                    try
                    {
                        // TODO: This currently results in a call to the synchronous TcpClient
                        // constructor, which is a blocking call, and can take a couple of seconds
                        // to connect (with timeouts and retries). This code is running on the UI
                        // thread. Ideally this should be connecting async, or moved off the UI thread.
                        this._networkClient = this._networkClientFactory.CreateNetworkClient(uri);

                        // Unclear if the above can succeed and not be connected, but check for safety.
                        // The code needs to either break out the while loop, or hit the retry logic
                        // in the exception handler.
                        if (this._networkClient.Connected)
                        {
                            LiveLogger.WriteLine("Debugger connected successfully");
                            break;
                        }
                        else
                        {
                            throw new SocketException();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.IsCriticalException())
                        {
                            throw;
                        }
                        LiveLogger.WriteLine("Connection attempt {0} failed with: {1}", connection_attempts, ex);
                        if (this._isClosed || connection_attempts >= MAX_ATTEMPTS)
                        {
                            throw;
                        }
                        else
                        {
                            // See above TODO. This should be moved off the UI thread or posted to retry
                            // without blocking in the meantime. For now, this seems the lesser of two
                            // evils. (The other being the debugger failing to attach on launch if the
                            // debuggee socket wasn't open quickly enough).
                            System.Threading.Thread.Sleep(200);
                        }
                    }
                }
            }

            Task.Factory.StartNew(this.ReceiveAndDispatchMessagesWorker);
            Task.Factory.StartNew(this.SendPacketsWorker);
        }
Ejemplo n.º 6
0
        public WorldInteraction(WorldModel world)
        {
            m_Network = ServiceRegistry.GetService<INetworkClient>();
            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();

            m_World = world;
        }
Ejemplo n.º 7
0
        public MainWindow(IButterflyWPFClient wpfClient,
                          ISnackbarController snackbarController,
                          INetworkClient networkClient,
                          IRegionManager regionManager)
        {
            InitializeComponent();

            Snackbar = this.MainSnackbar;

            networkClient.Connected += (sender, socket) =>
            {
                snackbarController.Enqueue($"Podłączono do serwera {socket.RemoteEndPoint}");
            };

            networkClient.Disconnected += (sender, socket) =>
            {
                snackbarController.Enqueue($"Rozłączono od serwera {socket.RemoteEndPoint}");
            };

            try
            {
                wpfClient.Start();
            }
            catch (Exception ex)
            {
                snackbarController.Enqueue(ex);
            }
        }
Ejemplo n.º 8
0
 internal Client(INetworkClient client, MatchConfig config) : base(client, config)
 {
     CurrentInput = new MatchInput(config);
     InputContext = new MatchInputContext(CurrentInput);
     NetworkClient.OnRecievedInputs += OnRecievedInputs;
     NetworkClient.OnRecievedState  += OnRecievedState;
 }
Ejemplo n.º 9
0
        public WorldInteraction(WorldModel world)
        {
            m_Network       = UltimaServices.GetService <INetworkClient>();
            m_UserInterface = UltimaServices.GetService <UserInterfaceService>();

            World = world;
        }
Ejemplo n.º 10
0
        internal static RequestClient Start(INetworkClient networkClient)
        {
            var client = new RequestClient(networkClient);

            client.StartReceiving();
            return(client);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Close connection.
 /// </summary>
 public void Close() {
     lock (_networkClientLock) {
         if (_networkClient != null) {
             _networkClient.Dispose();
             _networkClient = null;
         }
     }
 }
Ejemplo n.º 12
0
        protected override void Initialize()
        {
            base.Initialize();

            Container.Register(Window);

            _network = Container.Resolve <INetworkClient>();
        }
Ejemplo n.º 13
0
        public static void OnAuthenticationTicketMessage(INetworkClient client, AuthenticationTicketMessage im)
        {
            client.Send(new AuthenticationTicketAcceptedMessage());

            var accountId = client.GetEntity().GetComponent <AccountComponent>().AccountId;

            client.Send(new AccountCapabilitiesMessage(accountId));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Read a Base64 encoded line.
        /// </summary>
        /// <param name="client">The client to read from.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The decoded Base64 string.</returns>
        async Task <string> ReadBase64EncodedLineAsync(INetworkClient client, CancellationToken cancellationToken)
        {
            var text = await client.ReadLineAsync(Encoding.ASCII, cancellationToken).ConfigureAwait(false);

            return(text == null
                ? String.Empty
                : Encoding.UTF8.GetString(Convert.FromBase64String(text)));
        }
Ejemplo n.º 15
0
 public WorldCursor(WorldModel model)
 {
     _network       = Service.Get <INetworkClient>();
     _userInterface = Service.Get <UserInterfaceService>();
     _input         = Service.Get <IInputService>();
     _world         = model;
     InternalRegisterInteraction();
 }
Ejemplo n.º 16
0
 public User(INetworkClient _client)
 {
     this.client              = _client;
     this.UserVariables       = new Dictionary <string, IUserVariable>();
     client.DataReceived     += OnDataReceived;
     client.UserDisconnected += OnDisconnected;
     LogManager.GetCurrentClassLogger().Debug($"User connected!");
 }
Ejemplo n.º 17
0
 public void Remove(INetworkClient client)
 {
     lock (mutex)
     {
         clients.Remove(client.Id);
         client.Dispose();
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="options">The server options.</param>
 /// <param name="tcpClient">The TCP client that the session is connected with.</param>
 /// <param name="networkClient">The network client to use for communications.</param>
 internal SmtpSessionContext(ISmtpServerOptions options, TcpClient tcpClient, INetworkClient networkClient)
 {
     ServerOptions  = options;
     Transaction    = new SmtpMessageTransaction();
     RemoteEndPoint = tcpClient.Client.RemoteEndPoint;
     NetworkClient  = networkClient;
     Properties     = new Dictionary <string, object>();
 }
Ejemplo n.º 19
0
 public override Task <DemoRpcMessageResponse> ProcessRequestOnClient(INetworkClient client, DemoRpcMessage request)
 {
     Debug.Log($"Client got message: {request.message}");
     return(Task.FromResult(new DemoRpcMessageResponse()
     {
         success = true,
     }));
 }
Ejemplo n.º 20
0
        public void OnReceived(INetworkClient client, Packet receivedPacket)
        {
            string dataReceived = StringFromByteArr(receivedPacket.PacketRaw);

            Program.AddLog("Received: " + dataReceived);
            Program.g_MsgReceiver.ReceivedMsg(dataReceived);
            return;
        }
Ejemplo n.º 21
0
        public Task HandleAsync(INetworkClient client, ServerPacket packet)
        {
            client.IsReady = true;
            this.logger.LogDebug("Hello Packet Received");
            this.messageBus.Send("hello", client);

            return(Task.CompletedTask);
        }
Ejemplo n.º 22
0
 public override Task <DemoRpcSetUsernameResponse> ProcessRequestOnClient(INetworkClient client, DemoRpcSetUsername request)
 {
     return(Task.FromResult(new DemoRpcSetUsernameResponse()
     {
         success = false,
         errorMessage = "Not supported"
     }));
 }
Ejemplo n.º 23
0
        protected override void Initialize()
        {
            base.Initialize();

            Container.Register(Window);

            _network = Container.Resolve<INetworkClient>();
        }
Ejemplo n.º 24
0
        public MainWindowViewModel(IButterflyWPFClient wpfClient, INetworkClient netClient, WPFPingPacketHandler pingPacket)
            : base(wpfClient, netClient, pingPacket)
        {
            this.wpfClient.Start();


            this.ClickCommand = new DelegateCommand(this.Send);
        }
Ejemplo n.º 25
0
        public override void ReceivedPacket(INetworkClient client, AgentServerPacket packet)
        {
            Logger.Info("Received opcode: " + packet.Opcode + " (" + packet.Opcode.ToHex() + ")");

            switch (packet.Opcode)
            {
            case AgentServerOpcodes.Hello:
            {
                var unk0 = packet.Data.ReadUInt32();
                client.Account.ClientInstance = packet.Data.ReadUInt32();
                client.Account.Id             = packet.Data.ReadUInt32();

                var charId = (uint)0;      /*Database.ExecuteScalar<long>(
                                            * "SELECT characterid FROM clientinstances " +
                                            * "WHERE Accountid=" + client.Account.Id + " AND clientinst=" +
                                            * client.Account.ClientInstance);*/

                client.Character = new Character(charId);
                client.Character.LoadDetailsFromDatabase(Database);

                new ConanStream()
                .WriteUInt32(0x00050000)
                .Send(client);

                new ConanStream()
                .WriteUInt16(AgentServerRespondsOpcodes.Ox0014)
                .WriteArrayPrependLengthUInt16(new ConanStream()
                                               .WriteUInt32(client.Account.ClientInstance)
                                               .WriteUInt32(0x00000000)
                                               .WriteString(client.Character.Name.Length > 0
                                ? client.Character.Name
                                : "Character" + client.Account.ClientInstance))
                .Send(client);

                // "<localized category=20000 token=\"welcome_message\">"
                SendSystemMessage(client, Settings.WelcomeString);
                SendSystemMessage(client, Statics.BuildInfo.Replace("\n", "<br />"));

                new ConanStream()
                .WriteUInt16(AgentServerRespondsOpcodes.Ox003C)
                .WriteArrayPrependLengthUInt16(new ConanStream()
                                               .WriteByte(0x04)
                                               .WriteUInt32(0x0000232a)
                                               .WriteString("~Trial")
                                               .WriteUInt32(0x00008044)
                                               .WriteUInt16(0x0000))
                .Send(client);

                break;
            }

            default:
            {
                Logger.Warning("Unknown packet: " + packet);
                break;
            }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Writes a line to the client stream.
        /// </summary>
        /// <param name="client">The stream to write the line to.</param>
        /// <param name="text">The text to write to the client stream.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task which asynchronously performs the operation.</returns>
        public static Task WriteLineAsync(this INetworkClient client, string text, CancellationToken cancellationToken = default)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(WriteLineAsync(client, text, Encoding.ASCII, cancellationToken));
        }
Ejemplo n.º 27
0
        public WorldCursor(WorldModel model)
        {
            m_Network       = ServiceRegistry.GetService <INetworkClient>();
            m_UserInterface = ServiceRegistry.GetService <UserInterfaceService>();
            m_Input         = ServiceRegistry.GetService <InputManager>();

            m_World = model;
            InternalRegisterInteraction();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Read a line from the byte stream.
        /// </summary>
        /// <param name="client">The stream to write the line to.</param>
        /// <param name="text">The text to write to the client stream.</param>
        /// <param name="encoding">The encoding to use when converting the bytes to a text representation.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task which asynchronously performs the operation.</returns>
        public static Task WriteLineAsync(this INetworkClient client, string text, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.WriteAsync(encoding.GetBytes(text + Environment.NewLine), cancellationToken));
        }
Ejemplo n.º 29
0
 public InsecureNetworkNotification(
     INetworkClient networkClient,
     InsecureWifiNotificationViewModel insecureWifiNotificationViewModel,
     IEventAggregator eventAggregator)
 {
     _eventAggregator = eventAggregator;
     _insecureWifiNotificationViewModel = insecureWifiNotificationViewModel;
     networkClient.WifiChangeDetected  += OnWifiChangeDetected;
 }
Ejemplo n.º 30
0
        public WorldCursor(WorldModel model)
        {
            m_Network = ServiceRegistry.GetService<INetworkClient>();
            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_Input = ServiceRegistry.GetService<InputManager>();

            m_World = model;
            InternalRegisterInteraction();
        }
Ejemplo n.º 31
0
 public LocationApplicationService(IGatewayClient gatewayClient, ISensorClient sensorClient, INetworkClient networkClient, IMapper mapper,
                                   INetworkLocationClient networkLocationClient)
 {
     _sensorClient          = sensorClient;
     _gatewayClient         = gatewayClient;
     _networkClient         = networkClient;
     _mapper                = mapper;
     _networkLocationClient = networkLocationClient;
 }
Ejemplo n.º 32
0
 void Connect(string endpoint)
 {
     client = NetworkFactory.CreateNetworkClient <TcpNetworkClient> ();
     //client = NetworkFactory.CreateNetworkClient<RoomClientBridge> ();
     client.MessageHandler += (msg) => {
         RecieveMessage(msg);
     };
     client.Connect(endpoint);
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Channel{TController}"/> class.
 /// </summary>
 /// <param name="controller">The controller.</param>
 /// <param name="networkClient">The e.</param>
 public Channel(INetworkClient networkClient, IMessageParser messageParser, IMessageSerializer messageSerializer, ChannelControllerFactory <TChannelController> channelControllerFactory = null)
 {
     this.ChannelControllerFactory = channelControllerFactory ?? new ChannelControllerFactory <TChannelController>();
     this.InitializeNetworkClient(networkClient);
     this.InitializeSerializer(messageSerializer);
     this.InitializeNotifier();
     this.InitializeParser(messageParser);
     this.InitializeController();
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Writes a byte array to the underlying client stream.
        /// </summary>
        /// <param name="client">The stream to write the line to.</param>
        /// <param name="buffer">The byte array buffer to write to the client stream.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task which asynchronously performs the operation.</returns>
        public static Task WriteAsync(this INetworkClient client, byte[] buffer, CancellationToken cancellationToken = default)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(client.WriteAsync(new [] { new ArraySegment <byte>(buffer) }, cancellationToken));
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Read a line from the byte stream.
        /// </summary>
        /// <param name="client">The stream to read a line from.</param>
        /// <param name="timeout">The timeout to use whilst waiting for a line to be read.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The string that was read from the stream.</returns>
        public static Task <IReadOnlyList <ArraySegment <byte> > > ReadLineAsync(this INetworkClient client, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return(ReadLineAsync(client, cancellationToken).WithTimeout(timeout, cancellationToken));
        }
Ejemplo n.º 36
0
        public WorldInput(WorldModel world)
        {
            World = world;

            m_Network = ServiceRegistry.GetService<INetworkClient>();
            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_Input = ServiceRegistry.GetService<InputManager>();

            MousePick = new MousePicking();
        }
Ejemplo n.º 37
0
        public WorldInput(WorldModel world)
        {
            // parent reference
            World = world;

            // service references
            m_Network = ServiceRegistry.GetService<INetworkClient>();
            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_Input = ServiceRegistry.GetService<InputManager>();

            // local instances
            MousePick = new MousePicking();
            m_Macros = new MacroEngine();
        }
Ejemplo n.º 38
0
        // ============================================================================================================
        // Ctor, Initialization, Dispose, Update
        // ============================================================================================================
        public WorldModel()
        {
            Service.Add<WorldModel>(this);

            m_Engine = Service.Get<UltimaGame>();
            m_Network = Service.Get<INetworkClient>();
            m_UserInterface = Service.Get<UserInterfaceService>();

            Entities = new EntityManager(this);
            Entities.Reset(true);
            Effects = new EffectManager(this);
            Statics = new StaticManager();

            Input = new WorldInput(this);
            Interaction = new WorldInteraction(this);
            Client = new WorldClient(this);
        }
Ejemplo n.º 39
0
        public void AddSession(INetworkClient customClient)
        {
            Logger.Log.Info(Language.Instance.GetMessageFromKey("NEW_CONNECT") + customClient.ClientId);

            ClientSession session = IntializeNewSession(customClient);
            customClient.SetClientSession(session);

            if (session != null && IsWorldServer)
            {
                if (!_sessions.TryAdd(customClient.ClientId, session))
                {
                    Logger.Log.WarnFormat(Language.Instance.GetMessageFromKey("FORCED_DISCONNECT"), customClient.ClientId);
                    customClient.Disconnect();
                    _sessions.TryRemove(customClient.ClientId, out session);
                    return;
                }
            }
        }
Ejemplo n.º 40
0
        public DownloadSlotViewModel(DownloadSlot downloadSlot, INetworkClient downloadingClient,
            IFileStreamClient fileStreamClient)
        {
            if (downloadSlot == null)
                throw new ArgumentNullException("downloadSlot");
            if (downloadingClient == null)
                throw new ArgumentNullException("downloadingClient");
            if (fileStreamClient == null)
                throw new ArgumentNullException("fileStreamClient");

            this.downloadSlot = downloadSlot;
            this.downloadingClient = downloadingClient;
            this.fileStreamClient = fileStreamClient;

            this.downloadingClient.OnBlockDownloaded += downloadingClientOnBlockDownloaded;
            this.downloadingClient.OnError += downloadingClientOnError;
            this.downloadingClient.OnRestore += downloadingClientOnRestore;
            this.downloadingClient.OnComplete += downloadingClientOnComplete;
        }
Ejemplo n.º 41
0
 public void OnSent(INetworkClient client, SendStatus status)
 {
     switch (status)
     {
         case SendStatus.SUCCESS:
             Debug.WriteLine("SEND Success");
             break;
         case SendStatus.FAIL_CONNECTION_CLOSING:
             Debug.WriteLine("SEND failed due to connection closing");
             break;
         case SendStatus.FAIL_INVALID_PACKET:
             Debug.WriteLine("SEND failed due to invalid socket");
             break;
         case SendStatus.FAIL_NOT_CONNECTED:
             Debug.WriteLine("SEND failed due to no connection");
             break;
         case SendStatus.FAIL_SOCKET_ERROR:
             Debug.WriteLine("SEND Socket Error");
             break;
     }
 }
Ejemplo n.º 42
0
        public NachrichtenDispo(INetworkClient networkClient)
        {
            _networkClient = networkClient;

            // Rx :)
            incomingMessages = Observable.FromEventPattern<MessageReceivedEventHandler, MessageReceivedEventArgs>(
                h => _networkClient.MessageReceivedEvent += h,
                h => _networkClient.MessageReceivedEvent -= h)
                .Select(x => x.EventArgs.Content)
                .Where(ValidateMessage)
                .Where(x => GetMessageType(x) == MessageType.Reply)
                .Select(ParseResponse);

            incomingEvents = Observable.FromEventPattern<MessageReceivedEventHandler, MessageReceivedEventArgs>(
                h => _networkClient.MessageReceivedEvent += h,
                h => _networkClient.MessageReceivedEvent -= h)
                .Select(x => x.EventArgs.Content)
                .Where(ValidateMessage)
                .Where(x => GetMessageType(x) == MessageType.Event)
                .Select(ParseEvent);
        }
Ejemplo n.º 43
0
        public TopMenuGump()
            : base(0, 0)
        {
            IsUncloseableWithRMB = true;
            IsMoveable = true;

            // maximized view
            AddControl(new ResizePic(this, 0, 0, 9200, 610, 27), 1);
            AddControl(new Button(this, 5, 3, 5540, 5542, 0, 2, 0), 1);
            ((Button)LastControl).GumpOverID = 5541;
            // buttons are 2443 small, 2445 big
            // 30, 93, 201, 309, 417, 480, 543
            // map, paperdollB, inventoryB, journalB, chat, help, < ? >
            AddControl(new Button(this, 30, 3, 2443, 2443, ButtonTypes.Activate, 0, (int)Buttons.Map), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Map";
            AddControl(new Button(this, 93, 3, 2445, 2445, ButtonTypes.Activate, 0, (int)Buttons.Paperdoll), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Paperdoll";
            AddControl(new Button(this, 201, 3, 2445, 2445, ButtonTypes.Activate, 0, (int)Buttons.Inventory), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Inventory";
            AddControl(new Button(this, 309, 3, 2445, 2445, ButtonTypes.Activate, 0, (int)Buttons.Journal), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Journal";
            AddControl(new Button(this, 417, 3, 2443, 2443, ButtonTypes.Activate, 0, (int)Buttons.Chat), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Chat";
            AddControl(new Button(this, 480, 3, 2443, 2443, ButtonTypes.Activate, 0, (int)Buttons.Help), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Help";
            AddControl(new Button(this, 543, 3, 2443, 2443, ButtonTypes.Activate, 0, (int)Buttons.Question), 1);
            ((Button)LastControl).Caption = "<basefont color=#000000>Debug";
            // minimized view
            AddControl(new ResizePic(this, 0, 0, 9200, 30, 27), 2);
            AddControl(new Button(this, 5, 3, 5537, 5539, 0, 1, 0), 2);
            ((Button)LastControl).GumpOverID = 5538;

            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_World = ServiceRegistry.GetService<WorldModel>();
            m_Client = ServiceRegistry.GetService<INetworkClient>();

            MetaData.Layer = UILayer.Over;
        }
Ejemplo n.º 44
0
        public void RemoveSession(INetworkClient client)
        {
            ClientSession session;
            _sessions.TryRemove(client.ClientId, out session);

            // check if session hasnt been already removed
            if (session != null)
            {
                session.IsDisposing = true;

                if (IsWorldServer)
                {
                    if (session.HasSelectedCharacter)
                    {
                        if (session.Character.Hp < 1)
                        {
                            session.Character.Hp = 1;
                        }

                        if (ServerManager.Instance.Groups.Any(s => s.IsMemberOfGroup(session.Character.CharacterId)))
                        {
                            ServerManager.Instance.GroupLeave(session);
                        }

                        session.Character.Save();

                        // only remove the character from map if the character has been set
                        session.CurrentMap?.Broadcast(session, session.Character.GenerateOut(), ReceiverType.AllExceptMe);
                    }
                }

                session.Destroy();
                client.Disconnect();
                Logger.Log.Info(Language.Instance.GetMessageFromKey("DISCONNECT") + client.ClientId);
                session = null;
            }
        }
Ejemplo n.º 45
0
        private void BuildGump()
        {
            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_World = ServiceRegistry.GetService<WorldModel>();
            m_Client = ServiceRegistry.GetService<INetworkClient>();

            IsMoveable = true;
            SaveOnWorldStop = true;
            GumpLocalID = Mobile.Serial;

            if (Mobile.IsClientEntity)
            {
                AddControl(new GumpPic(this, 0, 0, 0x07d0, 0));

                // HELP
                AddControl(new Button(this, 185, 44 + 27 * 0, 0x07ef, 0x07f0, ButtonTypes.Activate, 0,
                    (int)Buttons.Help));
                ((Button)LastControl).GumpOverID = 0x07f1;
                // OPTIONS
                AddControl(new Button(this, 185, 44 + 27 * 1, 0x07d6, 0x07d7, ButtonTypes.Activate, 0,
                    (int)Buttons.Options));
                ((Button)LastControl).GumpOverID = 0x07d8;
                // LOG OUT
                AddControl(new Button(this, 185, 44 + 27 * 2, 0x07d9, 0x07da, ButtonTypes.Activate, 0,
                    (int)Buttons.LogOut));
                ((Button)LastControl).GumpOverID = 0x07db;
                // QUESTS
                AddControl(new Button(this, 185, 44 + 27 * 3, 0x57b5, 0x57b7, ButtonTypes.Activate, 0,
                    (int)Buttons.Quests));
                ((Button)LastControl).GumpOverID = 0x57b6;
                // SKILLS
                AddControl(new Button(this, 185, 44 + 27 * 4, 0x07df, 0x07e0, ButtonTypes.Activate, 0,
                    (int)Buttons.Skills));
                ((Button)LastControl).GumpOverID = 0x07e1;
                // GUILD
                AddControl(new Button(this, 185, 44 + 27 * 5, 0x57b2, 0x57b4, ButtonTypes.Activate, 0,
                    (int)Buttons.Guild));
                ((Button)LastControl).GumpOverID = 0x57b3;
                // PEACE / WAR
                m_IsWarMode = Mobile.Flags.IsWarMode;
                int[] btngumps = m_IsWarMode ? WarModeBtnGumps : PeaceModeBtnGumps;
                m_WarModeBtn = (Button)AddControl(new Button(this, 185, 44 + 27 * 6, btngumps[0], btngumps[1], ButtonTypes.Activate, 0,
                    (int)Buttons.PeaceWarToggle));
                ((Button)LastControl).GumpOverID = btngumps[2];
                // STATUS
                AddControl(new Button(this, 185, 44 + 27 * 7, 0x07eb, 0x07ec, ButtonTypes.Activate, 0,
                    (int)Buttons.Status));
                ((Button)LastControl).GumpOverID = 0x07ed;

                // Virtue menu
                AddControl(new GumpPic(this, 80, 8, 0x0071, 0));
                LastControl.MouseDoubleClickEvent += VirtueMenu_MouseDoubleClickEvent;

                // Special moves book
                // AddControl(new GumpPic(this, 158, 200, 0x2B34, 0));
                // LastControl.MouseDoubleClickEvent += SpecialMoves_MouseDoubleClickEvent;

                // equipment slots for hat/earrings/neck/ring/bracelet
                AddControl(new EquipmentSlot(this, 2, 76, Mobile, EquipLayer.Helm));
                AddControl(new EquipmentSlot(this, 2, 76 + 22 * 1, Mobile, EquipLayer.Earrings));
                AddControl(new EquipmentSlot(this, 2, 76 + 22 * 2, Mobile, EquipLayer.Neck));
                AddControl(new EquipmentSlot(this, 2, 76 + 22 * 3, Mobile, EquipLayer.Ring));
                AddControl(new EquipmentSlot(this, 2, 76 + 22 * 4, Mobile, EquipLayer.Bracelet));

                // Paperdoll control!
                AddControl(new PaperDollInteractable(this, 8, 21)
                {
                    SourceEntity = Mobile
                });
            }
            else
            {
                AddControl(new GumpPic(this, 0, 0, 0x07d1, 0));

                // Paperdoll
                AddControl(new PaperDollInteractable(this, 8, 21)
                {
                    SourceEntity = Mobile
                });
            }

            // name and title
            AddControl(new HtmlGumpling(this, 36, 262, 180, 42, 0, 0, string.Format("<span color=#aaa style='font-family:uni0;'>{0}", Mobile.Name)));
            AddControl(new HtmlGumpling(this, 35, 262, 180, 42, 0, 0, string.Format("<span color=#222 style='font-family:uni0;'>{0}", Mobile.Name)));
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Receive callback
 /// </summary>
 /// <param name="client">client</param>
 /// <param name="receivedPacket">received packet</param>
 public void OnReceived(INetworkClient client, Packet receivedPacket)
 {
     ParallelPacket receivedParallelPacket = new ParallelPacket(receivedPacket);
     switch (receivedParallelPacket.PacketType)
     {
         case ParallelPacketType.DATA:
             if (ReceiveType == ReceiveType.BURST)
             {
                 OnParallelClientReceived(this, receivedParallelPacket);
             }
             else if (m_receiveType == ReceiveType.SEQUENTIAL)
             {
                 lock (m_receiveLock)
                 {
                     m_receivedQueue.Enqueue(receivedParallelPacket);
                     while (!m_receivedQueue.IsEmpty() && m_curReceivedPacketId + 1 == m_receivedQueue.Peek().PacketID)
                     {
                         ParallelPacket curPacket = m_receivedQueue.Dequeue();
                         m_curReceivedPacketId = curPacket.PacketID;
                         if (m_curReceivedPacketId == long.MaxValue)
                         {
                             m_curReceivedPacketId = -1;
                         }
                         OnParallelClientReceived(this, curPacket);
                     }
                 }
             }
             break;
         case ParallelPacketType.IDENTITY_REQUEST:
             PacketSerializer<IdentityResponse> serializer = new PacketSerializer<IdentityResponse>(new IdentityResponse(Guid,MaxSocketCount));
             ParallelPacket sendPacket=new ParallelPacket(-1,ParallelPacketType.IDENTITY_RESPONSE,serializer.PacketRaw);
             client.Send(sendPacket.PacketRaw);
             break;
         case ParallelPacketType.READY:
             lock (m_sendLock)
             {
                 m_pendingClientSet.Add(client);
                 if (m_pendingClientSet.Count > 0 && (m_errorPacketSet.Count > 0 || m_packetQueue.Count > 0))
                     m_sendReadyEvent.SetEvent();
             }
             break;
     }
 }
Ejemplo n.º 47
0
 private void SetUpIoC()
 {
     _networkClient = new NetworkClient();
     _nachrichtenDispo = new NachrichtenDispo(_networkClient);
     _basicClient = new BasicClient(NachrichtenDispo);
 }
Ejemplo n.º 48
0
        /// <summary>
        /// Initialises a new instance of the <see cref="IrcClient"/> class.
        /// </summary>
        /// <param name="client">
        /// The client.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="ircConfiguration">
        /// The configuration Helper.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        public IrcClient(INetworkClient client, ILogger logger, IIrcConfiguration ircConfiguration, string password)
        {
            this.nickname = ircConfiguration.Nickname;
            this.networkClient = client;
            this.logger = logger;
            this.syncLogger = logger.CreateChildLogger("Sync");
            this.username = ircConfiguration.Username;
            this.realName = ircConfiguration.RealName;
            this.password = password;
            this.networkClient.DataReceived += this.NetworkClientOnDataReceived;
            this.ReceivedMessage += this.OnMessageReceivedEvent;

            this.clientCapabilities = new List<string> { "sasl", "account-notify", "extended-join", "multi-prefix" };

            this.authToServices = ircConfiguration.AuthToServices;

            if (!this.authToServices)
            {
                this.logger.Warn("Services authentication is disabled!");

                this.clientCapabilities.Remove("sasl");
                this.clientCapabilities.Remove("account-notify");
                this.clientCapabilities.Remove("extended-join");
            }

            this.userCache = new Dictionary<string, IrcUser>();
            this.channels = new Dictionary<string, IrcChannel>();

            this.connectionRegistrationSemaphore = new Semaphore(0, 1);
            this.syncLogger.Debug("ctor() acquired connectionRegistration semaphore.");

            this.RegisterConnection(null);
        }
Ejemplo n.º 49
0
        public PaperDollGump(Mobile parent)
            : base(parent.Serial, 0)
        {
            Parent = parent;

            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_World = ServiceRegistry.GetService<WorldModel>();
            m_Client = ServiceRegistry.GetService<INetworkClient>();

            IsMovable = true;

            if (parent == (Mobile)WorldModel.Entities.GetPlayerObject())
            {
                AddControl(new GumpPic(this, 0, 0, 0x07d0, 0));

                // HELP
                AddControl(new Button(this, 185, 44 + 27*0, 0x07ef, 0x07f0, ButtonTypes.Activate, 0,
                    (int) Buttons.Help));
                ((Button) LastControl).GumpOverID = 0x07f1;
                // OPTIONS
                AddControl(new Button(this, 185, 44 + 27*1, 0x07d6, 0x07d7, ButtonTypes.Activate, 0,
                    (int) Buttons.Options));
                ((Button) LastControl).GumpOverID = 0x07d8;
                // LOG OUT
                AddControl(new Button(this, 185, 44 + 27*2, 0x07d9, 0x07da, ButtonTypes.Activate, 0,
                    (int) Buttons.LogOut));
                ((Button) LastControl).GumpOverID = 0x07db;
                // QUESTS
                AddControl(new Button(this, 185, 44 + 27*3, 0x57b5, 0x57b7, ButtonTypes.Activate, 0,
                    (int) Buttons.Quests));
                ((Button) LastControl).GumpOverID = 0x57b6;
                // SKILLS
                AddControl(new Button(this, 185, 44 + 27*4, 0x07df, 0x07e0, ButtonTypes.Activate, 0,
                    (int) Buttons.Skills));
                ((Button) LastControl).GumpOverID = 0x07e1;
                // GUILD
                AddControl(new Button(this, 185, 44 + 27*5, 0x57b2, 0x57b4, ButtonTypes.Activate, 0,
                    (int) Buttons.Guild));
                ((Button) LastControl).GumpOverID = 0x57b3;
                // PEACE / WAR
                AddControl(new Button(this, 185, 44 + 27*6, 0x07e5, 0x07e6, ButtonTypes.Activate, 0,
                    (int) Buttons.PeaceWarToggle));
                ((Button) LastControl).GumpOverID = 0x07e7;
                // STATUS
                AddControl(new Button(this, 185, 44 + 27*7, 0x07eb, 0x07ec, ButtonTypes.Activate, 0,
                    (int) Buttons.Status));
                ((Button) LastControl).GumpOverID = 0x07ed;

                // Paperdoll
                AddControl(new PaperDollInteractable(this, 8, 21)
                {
                    SourceEntity = Parent
                });
            }
            else
            {
                AddControl(new GumpPic(this, 0, 0, 0x07d1, 0));

                // Paperdoll
                AddControl(new PaperDollInteractable(this, 8, 21)
                {
                    SourceEntity = Parent
                });
            }
        }
Ejemplo n.º 50
0
 public void RemoveClient(INetworkClient client)
 {
     this.clients.Remove(client);
 }
Ejemplo n.º 51
0
 public void AddClient(INetworkClient client)
 {
     this.clients.Add(client);
 }
Ejemplo n.º 52
0
        /// <summary>
        /// Disconnect callback
        /// </summary>
        /// <param name="client">client</param>
        public void OnDisconnect(INetworkClient client)
        {
            lock (m_generalLock)
            {
                m_clientSet.Remove(client);

                lock (m_sendLock)
                {
                    m_pendingClientSet.Remove(client);
                }

                CurSocketCount--;
                if (CurSocketCount <= 0)
                {
                    lock (m_sendLock)
                    {
                        m_packetQueue.Clear();
                        m_pendingPacketSet.Clear();
                        m_errorPacketSet.Clear();
                    }
                    lock (m_receiveLock)
                    {
                        m_receivedQueue.Clear();
                    }
                    m_sendReadyEvent.SetEvent();
                    IsConnectionAlive = false;
                    Task t = new Task(delegate()
                    {
                        OnParallelClientDisconnect(this);
                    });
                    t.Start();

                }
            }
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Ensures the client.
 /// </summary>
 /// <param name="applicationIdentifier">The application identifier.</param>
 private void EnsureClient(string applicationIdentifier)
 {
     if (this.networkClient == null)
     {
         this.networkClient = this.factory.CreateNetworkClient(applicationIdentifier);
         this.networkClient.HostConnected += (sender, host) => this.OnHostConnected(host);
         this.networkClient.HostDisconnected += (sender, host) => this.OnHostDisconnected(host);
         this.networkClient.HostDiscovered += (sender, host) => this.OnHostDiscovered(host);
         this.networkClient.MessageReceived += (sender, message) => this.OnClientMessageReceived(message);
     }
 }
Ejemplo n.º 54
0
 public void OnDisconnect(INetworkClient client)
 {
     tbHostname.Enabled = true;
     tbPort.Enabled = true;
     btnConnect.Text = "Connect";
     tbSend.Enabled = false;
     btnSend.Enabled = false;
     MessageBox.Show("Disconnected from the server!");
 }
Ejemplo n.º 55
0
 /// <summary>
 /// Send callback
 /// </summary>
 /// <param name="client">client</param>
 /// <param name="status">send status</param>
 public void OnSent(INetworkClient client, SendStatus status, Packet sentPacket)
 {
     ParallelPacket sentParallelPacket = ParallelPacket.FromPacket(sentPacket);
     if (sentParallelPacket.PacketType == ParallelPacketType.DATA)
     {
         lock (m_sendLock)
         {
             m_pendingPacketSet.Remove(sentParallelPacket);
             if (status == SendStatus.SUCCESS || status == SendStatus.FAIL_INVALID_PACKET)
             {
                 m_pendingClientSet.Add(client);
             }
             if (status != SendStatus.SUCCESS)
             {
                 m_errorPacketSet.Add(sentParallelPacket);
             }
             if (m_pendingClientSet.Count > 0 && (m_errorPacketSet.Count > 0 || m_packetQueue.Count > 0))
                 m_sendReadyEvent.SetEvent();
         }
         
         Task t = new Task(delegate()
         {
             OnParallelClientSent(this, status, sentParallelPacket);
         });
         t.Start();
         
     
     }
 }
Ejemplo n.º 56
0
        /// <summary>
        /// Connect to specified debugger endpoint.
        /// </summary>
        /// <param name="uri">URI identifying the endpoint to connect to.</param>
        public void Connect(Uri uri) {
            Utilities.ArgumentNotNull("uri", uri);

            Close();
            lock (_networkClientLock) {
                _networkClient = _networkClientFactory.CreateNetworkClient(uri);
            }

            Task.Factory.StartNew(ReceiveAndDispatchMessagesWorker);
            Task.Factory.StartNew(SendPacketsWorker);
        }
Ejemplo n.º 57
0
 public void OnConnected(INetworkClient client, ConnectStatus status)
 {
     MessageBox.Show("Connected to the server!");
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Connect to specified debugger endpoint.
        /// </summary>
        /// <param name="uri">URI identifying the endpoint to connect to.</param>
        public void Connect(Uri uri) {
            Utilities.ArgumentNotNull("uri", uri);
            LiveLogger.WriteLine("Debugger connecting to URI: {0}", uri);

            Close();
            lock (_networkClientLock) {
                int connection_attempts = 0;
                const int MAX_ATTEMPTS = 5;
                while (true) {
                    connection_attempts++;
                    try {
                        // TODO: This currently results in a call to the synchronous TcpClient
                        // constructor, which is a blocking call, and can take a couple of seconds
                        // to connect (with timeouts and retries). This code is running on the UI
                        // thread. Ideally this should be connecting async, or moved off the UI thread.
                        _networkClient = _networkClientFactory.CreateNetworkClient(uri);

                        // Unclear if the above can succeed and not be connected, but check for safety.
                        // The code needs to either break out the while loop, or hit the retry logic
                        // in the exception handler.
                        if (_networkClient.Connected) {
                            LiveLogger.WriteLine("Debugger connected successfully");
                            break;
                        }
                        else {
                            throw new SocketException();
                        }
                    }
                    catch (Exception ex) {
                        if (ex.IsCriticalException()) {
                            throw;
                        }
                        LiveLogger.WriteLine("Connection attempt {0} failed with: {1}", connection_attempts, ex);
                        if (_isClosed || connection_attempts >= MAX_ATTEMPTS) {
                            throw;
                        }
                        else {
                            // See above TODO. This should be moved off the UI thread or posted to retry
                            // without blocking in the meantime. For now, this seems the lesser of two
                            // evils. (The other being the debugger failing to attach on launch if the
                            // debuggee socket wasn't open quickly enough).
                            System.Threading.Thread.Sleep(200);
                        }
                    }
                }
            }

            Task.Factory.StartNew(ReceiveAndDispatchMessagesWorker);
            Task.Factory.StartNew(SendPacketsWorker);
        }
Ejemplo n.º 59
0
 protected virtual ClientSession IntializeNewSession(INetworkClient client)
 {
     ClientSession session = new ClientSession(client);
     client.SetClientSession(session);
     return session;
 }
Ejemplo n.º 60
0
 public void OnReceived(INetworkClient client, Packet receivedPacket)
 {
     string sendString = StringFromByteArr(receivedPacket.GetPacket()) + "\r\n";
     AddMsg(sendString);
 }