// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoServerInstance"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <param name="address">The address.</param> internal MongoServerInstance(MongoServerSettings settings, MongoServerAddress address) { _settings = settings; _address = address; _sequentialId = Interlocked.Increment(ref __nextSequentialId); _state = MongoServerState.Disconnected; _serverInfo = new ServerInformation { MaxDocumentSize = MongoDefaults.MaxDocumentSize, MaxMessageLength = MongoDefaults.MaxMessageLength, InstanceType = MongoServerInstanceType.Unknown }; _connectionPool = new MongoConnectionPool(this); _pingTimeAggregator = new PingTimeAggregator(5); _permanentlyDisconnected = false; // Console.WriteLine("MongoServerInstance[{0}]: {1}", sequentialId, address); _stateVerificationAcquireConnectionOptions = new MongoConnectionPool.AcquireConnectionOptions { OkToAvoidWaitingByCreatingNewConnection = false, OkToExceedMaxConnectionPoolSize = true, OkToExceedWaitQueueSize = true, WaitQueueTimeout = TimeSpan.FromSeconds(2) }; }
public void SetSelectedServer(string name) { if (this.SelectedServer?.Name != name) { this.SelectedServer = this.storage.Servers.FirstOrDefault(x => x.Name == name); this.SelectedServerChanged?.Invoke(this, EventArgs.Empty); } }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoServerInstance"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <param name="address">The address.</param> internal MongoServerInstance(MongoServerSettings settings, MongoServerAddress address) { _settings = settings; _address = address; _sequentialId = Interlocked.Increment(ref __nextSequentialId); _state = MongoServerState.Disconnected; _serverInfo = new ServerInformation { MaxDocumentSize = MongoDefaults.MaxDocumentSize, MaxMessageLength = MongoDefaults.MaxMessageLength, InstanceType = MongoServerInstanceType.Unknown }; _connectionPool = new MongoConnectionPool(this); _pingTimeAggregator = new PingTimeAggregator(5); _permanentlyDisconnected = false; // Console.WriteLine("MongoServerInstance[{0}]: {1}", sequentialId, address); }
/// <summary> /// Load the textual properties into a list box /// </summary> private void LoadProperties() { listViewProperties.Columns.Add("Key"); listViewProperties.Columns.Add("Value"); foreach (KeyValuePair <string, string> pair in m_properties) { ListViewItem item = listViewProperties.Items.Add(pair.Key); item.SubItems.Add(pair.Value); } try { /* Also add IObjectSafety information if available */ IObjectSafety objSafety = m_pObject as IObjectSafety; if (objSafety != null) { uint supportedOptions; uint enabledOptions; Guid iid = COMInterfaceEntry.IID_IDispatch; objSafety.GetInterfaceSafetyOptions(ref iid, out supportedOptions, out enabledOptions); for (int i = 0; i < 4; i++) { int val = 1 << i; if ((val & supportedOptions) != 0) { ListViewItem item = listViewProperties.Items.Add(Enum.GetName(typeof(ObjectSafetyFlags), val)); } } } } catch { } ServerInformation info = COMUtilities.GetServerInformation(m_pObject); if (info.dwServerPid != 0) { listViewProperties.Items.Add("Server PID").SubItems.Add(info.dwServerPid.ToString()); listViewProperties.Items.Add("Server TID").SubItems.Add(info.dwServerTid.ToString()); listViewProperties.Items.Add("Server Address").SubItems.Add(string.Format("0x{0:X}", info.ui64ServerAddress)); } listViewProperties.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); }
static void Main(string[] args) { _RemotingClient = new RemotingClient(); s = new ServerInformation(); s.serverName = "S1"; theCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); theMemCounter = new PerformanceCounter("Memory", "Available MBytes"); Thread thread1 = new Thread(new ThreadStart(SendServerPerformance)); thread1.Start(); Console.ReadLine(); }
private void Add([NotNull] ServerInformation information) { var existing = _list.GetByIdOrDefault(information.Id); if (existing == null) { var entry = new ServerEntry(information); entry.SetOrigin(Key); entry.SetReferences(FileBasedOnlineSources.Instance.GetSourceKeys(entry)); _list.Add(entry); } else { existing.SetOrigin(Key); existing.UpdateValues(information); } }
public void SetServerInformation(ServerInformation serverInformation) { var allhost = GetAllHostAvailable(); if (!allhost.Contains(serverInformation.ServerName)) { AddServer(serverInformation.ServerName); } var command = new SqlCommand(ConfigurationManager.AppSettings["SetServerInformation"], mySqlConnection); command.Parameters.AddWithValue("@hostName", serverInformation.ServerName); command.Parameters.AddWithValue("@processorUsage", serverInformation.ProcessorUsage); command.Parameters.AddWithValue("@memoryUsage", serverInformation.MemoryUsage); command.Parameters.AddWithValue("@time", serverInformation.Time); RunNonQuery(command); }
public static async Task<HttpClient> TestServerAsync(ServerInformation server) { foreach (var address in server.Addresses) { var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.BaseAddress = new Uri(address); var result = await GetTokenAsync(client, server); if (result) { return client; } } return null; }
public void InfoMessageHandler(ConnectionEventArgs a) { Message m = a.GetMessage(); if (m == null) { return; } if (m is ServerInformationRequest) { Connection c = a.GetConnection(); ServerInformation smsg = new ServerInformation(Name, _devices.GetEnumerator()); try { c.Send(smsg); } catch (Exception) { } } else if (m is RegisterDevice) { RegisteredDevice dev = new RegisteredDevice((RegisterDevice)m); if (_registeredDevices[dev.Port] == null) { _registeredDevices[dev.Port] = dev; _devices.Add(dev); serverStateChanged(true, dev); } } else if (m is UnregisterDevice) { RegisteredDevice dev = (RegisteredDevice) _registeredDevices[((UnregisterDevice)m).GetDevicePort()]; if (dev != null) { _registeredDevices.Remove(dev); _devices.Remove(dev); serverStateChanged(false, dev); } } }
public bool IsDifferentFrom(ServerInformation other) { if (InstanceType != other.InstanceType) { return(true); } if (IsPrimary != other.IsPrimary) { return(true); } if (IsSecondary != other.IsSecondary) { return(true); } if (IsPassive != other.IsPassive) { return(true); } if (IsArbiter != other.IsArbiter) { return(true); } if (MaxDocumentSize != other.MaxDocumentSize) { return(true); } if (MaxMessageLength != other.MaxMessageLength) { return(true); } if ((ReplicaSetInformation == null && other.ReplicaSetInformation != null) || (ReplicaSetInformation != other.ReplicaSetInformation)) { return(true); } return(false); }
public ServerEntry([NotNull] ServerInformation information) { if (information == null) { throw new ArgumentNullException(nameof(information)); } _sortingName = Lazier.Create(() => GetSortingName(DisplayName)); Id = information.Id; Ip = information.Ip; PortHttp = information.PortHttp; Ping = null; PrepareErrorsList(); var status = UpdateValues(information, true, true); Status = status == ServerStatus.MissingContent ? ServerStatus.Unloaded : status ?? ServerStatus.Unloaded; UpdateErrorsList(); }
private void SendServerInfo(MemoryMappedFileCommunicator communicator) { if (Info == null) { Info = new ServerInformation { ServerConfig = Config, MonsterTemplates = new List <MonsterTemplate>(GlobalMonsterTemplateCache), ItemTemplates = new List <ItemTemplate>(GlobalItemTemplateCache.Select(i => i.Value)), SkillTemplates = new List <SkillTemplate>(GlobalSkillTemplateCache.Select(i => i.Value)), SpellTemplates = new List <SpellTemplate>(GlobalSpellTemplateCache.Select(i => i.Value)), MundaneTemplates = new List <MundaneTemplate>(GlobalMundaneTemplateCache.Select(i => i.Value)), WarpTemplates = new List <WarpTemplate>(GlobalWarpTemplateCache), Areas = new List <Area>(GlobalMapCache.Select(i => i.Value)), Buffs = new List <Buff>(GlobalBuffCache.Select(i => i.Value)), Debuffs = new List <Debuff>(GlobalDeBuffCache.Select(i => i.Value)), }; } Info.GameServerOnline = true; Info.LoginServerOnline = true; var players_online = Game?.Clients.Where(i => i != null && i.Aisling != null && i.Aisling.LoggedIn); if (players_online != null) { Info.PlayersOnline = new List <Aisling>(players_online.Select(i => i.Aisling)); Info.GameServerStatus = $"Up time {Math.Round(Uptime.TotalDays, 2)}:{Math.Round(Uptime.TotalHours, 2)} | Online Users ({ players_online.Count() }) | Total Characters ({ StorageManager.AislingBucket.Count })"; Info.GameServerOnline = true; } else { Info.PlayersOnline = new List <Aisling>(); Info.GameServerOnline = false; Info.GameServerStatus = "Offline."; } lock (communicator) { var jsonWrap = JsonConvert.SerializeObject(Info, StorageManager.Settings); communicator.Write(jsonWrap); } }
public ServerEntry([NotNull] ServerInformation information) { if (information == null) { throw new ArgumentNullException(nameof(information)); } Id = information.Id; Ip = information.Ip; PortHttp = information.PortHttp; Ping = null; var errors = new List <string>(3); var status = UpdateValues(information, errors, true); Status = status ?? ServerStatus.Unloaded; Errors = errors; }
public ServerController(ModdableChessGame game) { game.AddTicking(this); info = game.Components.GetOrRegister <ServerInformation>((int)ComponentKeys.ServerInformation, ServerInformation.Create); ClearServerInfo(); game.Components.Register((int)ComponentKeys.Server_Callbacks, this); game.Components.GetOrRegister <Query <bool, StartHostCommand> >((int)ComponentKeys.StartHostCommand, Query <bool, StartHostCommand> .Create) .Handler = StartHost; game.Components.GetOrRegister <Command>((int)ComponentKeys.StopHostCommand, Command.Create) .Handler = StopHost; info.Connection.EnterStateMessenger.Subscribe(new SimpleListener <int>((s) => UnityEngine.Debug.LogError(string.Format("{0}: Server connection change {1}", game.TickCount, (ServerConnectionState)s)))); disconnectNextFrame = new Queue <int>(); //new ReconnectionServerManager(game); //new ServerReadyCheckManager(game); //new ServerLoadingErrorManager(game); }
private static async Task<bool> GetTokenAsync(HttpClient client, ServerInformation server) { try { var content = new StringContent($"grant_type=password&username={server.Username}&password={server.Password}"); var response = await client.PostAsync("api/account/token", content); var result = await response.Content.ReadAsStringAsync(); var deserializedResult = JsonConvert.DeserializeObject<LoginTokenResponse>(result); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", deserializedResult.access_token); if (response.IsSuccessStatusCode) { return true; } } catch { } return false; }
public void SendServerCost(ServerInformation s) { if (s.serverName == "S1") { S1 = s; Console.WriteLine("Server 1: Memory={0}, CPU={1}", S1.AvailableRam, S1.CpuUsage); } if (s.serverName == "S2") { S2 = s; Console.WriteLine("Server 2: Memory={0}, CPU={1}", S2.AvailableRam, S2.CpuUsage); } if (s.serverName == "S3") { S3 = s; Console.WriteLine("Server 3: Memory={0}, CPU={1}", S3.AvailableRam, S3.CpuUsage); } Console.WriteLine("*******"); }
public async Task <List <ServerInformation> > ServerInformationList(string Name, List <ServerInformationProvidersType> Providers) { List <ServerInformation> serversInformation = new List <ServerInformation>(); InformationProviderFactory factory = null; foreach (ServerInformationProvidersType provider in Providers) { switch (provider) { case ServerInformationProvidersType.GeoIp: factory = new GeoIpInformationProviderFactory(); break; case ServerInformationProvidersType.RDap: factory = new RDapInformationProviderFactory(); break; case ServerInformationProvidersType.ReverseDNS: factory = new RDnsInformationProviderFactory(); break; case ServerInformationProvidersType.Ping: factory = new PingInformationProviderFactory(); break; default: break; } ServerInformation information = new ServerInformation(); ServerInformationProvider informationProvider = factory.GetInformationProvider(); information.Name = Name; information.InformationProvider = provider; information.Information = await informationProvider.GetInformation(Name); serversInformation.Add(information); } return(serversInformation); }
/// <summary> /// Erstellt einen neuen Zustand. /// </summary> /// <param name="target">Das aktuelle Ziel des Datenversands.</param> /// <param name="server">Die zugehörigen Informationen des Aufzeichnungsprozesses.</param> /// <returns>Der gwünschte Zustand.</returns> public static ZappingStatus Create(string target, ServerInformation server) { // Create new var status = new ZappingStatus { Target = target, Services = s_NoServices }; // No state if (server == null) { return(status); } // Attach to the first stream var streams = server.Streams; if (streams != null) { if (streams.Count > 0) { status.Source = SourceIdentifier.ToString(streams[0].Source).Replace(" ", ""); } } // Fill in NVOD services in the standard index order var services = server.Services; if (services != null) { status.Services = services .Where(service => service != null) .Select(ZappingService.Create) .OrderBy(service => service.Index) .ToArray(); } // Report return(status); }
public async Task <BitmapImage> FetchServerBanner(ServerInformation serverInformation) { var banner = new BitmapImage(); if (serverInformation.BannerUrl.Length == 0) { banner.BeginInit(); banner.UriSource = new Uri("/Resources/Banners/Default_Banner.png", UriKind.Relative); banner.EndInit(); } else { var data = await WebManager.Client.GetByteArrayAsync(serverInformation.BannerUrl); banner.BeginInit(); banner.CacheOption = BitmapCacheOption.OnLoad; banner.StreamSource = new MemoryStream(data); banner.EndInit(); } return(banner); }
/// <summary> /// Aktiviert eine neue Quelle. /// </summary> /// <typeparam name="TStatus">Die Art der Zustandsinformation.</typeparam> /// <param name="source">Die gewünschte Quelle.</param> /// <param name="factory">Methode zum Erzeugen einer neuen Zustandsinformation.</param> /// <returns>Der neue Zustand der Übertragung.</returns> public TStatus SetSource <TStatus>(SourceIdentifier source, Func <string, ServerInformation, TStatus> factory) { // Update end time Stamp(); // Remap to real source var selection = VCRProfiles.FindSource(ProfileName, source); if (selection == null) { throw new ArgumentNullException("source"); } // Report Tools.ExtendedLogging("Will now zap to Source {0}", selection.Source); // Process and remember m_lastState = EnqueueActionAndWait(() => ServerImplementation.EndRequest(Server.BeginSetZappingSource(selection.SelectionKey, m_target))); // Report return(CreateStatus(factory)); }
public void ConnectAsync_Successful_ConnectsClientAndSetsProperties() { const string hostname = "localhost"; const int port = 6667; const string nickname = "hax2themax"; var serverInfo = new ServerInformation { HostName = hostname, Port = port }; var registrationInfo = new RegistrationInformation { Nickname = nickname }; _mockTcpClient.Setup(tcp => tcp.Connect(hostname, port)).Verifiable(); _mockClient.Setup(f => f.HandleConnectionAsync(registrationInfo)).Returns(Task.Delay(0)).Verifiable(); _client.ConnectAsync(serverInfo, registrationInfo).Wait(); Assert.AreEqual(serverInfo, _client.ServerInformation); Assert.AreEqual(nickname, _client.Nickname); }
private async Task DownloadServerInformationAsync() { FileDownloadStarted?.Invoke(this, EventArgs.Empty); try { await DownloadFile(new Uri(Settings.Values.ServerInformationUri), Path.Combine(Directory.GetCurrentDirectory(), Constants.ServerConfigFileName)); // Now we try to open and deserialize the file into ServerInformation var fileContents = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), Constants.ServerConfigFileName)); if (String.IsNullOrEmpty(fileContents)) { ServerFileFormatError?.Invoke(this, EventArgs.Empty); return; } FileDownloadFinished?.Invoke(this, EventArgs.Empty); ServerInformation info = JsonConvert.DeserializeObject <ServerInformation>(fileContents); if (info == null) { ServerFileFormatError?.Invoke(this, EventArgs.Empty); return; } DownloadedInformation = info; DownloadAndParseNews(info.NewsUri); ParseServerFileInformation(info); } catch (Exception ex) { FileDownloadFinished?.Invoke(this, EventArgs.Empty); ConnectionToServerError?.Invoke(this, EventArgs.Empty); } }
static void CheckInfo(ServerInformation serverInformation) { Assert.IsNotNull(serverInformation.SwarmServers); Assert.AreEqual(3, serverInformation.SwarmServers.Count); var node1 = serverInformation.SwarmServers.SingleOrDefault(x => x.Identifier == "node1"); Assert.IsNotNull(node1); Assert.AreEqual(node1.Address, "http://localhost:5012"); Assert.IsFalse(node1.Controller); var node2 = serverInformation.SwarmServers.SingleOrDefault(x => x.Identifier == "node2"); Assert.IsNotNull(node2); Assert.AreEqual(node2.Address, "http://localhost:5013"); Assert.IsFalse(node2.Controller); var controller = serverInformation.SwarmServers.SingleOrDefault(x => x.Identifier == "controller"); Assert.IsNotNull(controller); Assert.AreEqual(controller.Address, "http://localhost:5011"); Assert.IsTrue(controller.Controller); }
public async Task <ActionResult> ServerInformation() { ServerInformation Information = new ServerInformation(); try { using (StreamReader streamReader = new StreamReader(configFile)) { string FileData = await streamReader.ReadToEndAsync(); Information = JsonConvert.DeserializeObject <ServerInformation>(FileData, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include, MissingMemberHandling = MissingMemberHandling.Ignore }); } } catch { Information = new ServerInformation(); } return(View(Information)); }
private async void HandleLogin(object obj) { var passwordBox = obj as PasswordBox; var password = passwordBox.Password; var server = new ServerInformation { Addresses = new List<string> { this.settings.Address }, Password = password, Username = this.Username }; var client = await ServerTester.TestServerAsync(server); if (client == null) { NotificationsHost.Error("Грешно име или парола", "Въведените парола или име са невалидни."); } else { ViewModelLocator.httpClient = client; ViewModelLocator.Container.Resolve<MainWindowViewModel>().ShowSell(); } }
private static async Task <Boolean> AddServer() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; // Update port # in the following line. client.BaseAddress = new Uri("http://localhost:44362/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.Timeout = TimeSpan.FromMinutes(30); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; try { // Create a new product ServerInformation SI = new ServerInformation { Name = "John", Address = "66.44.22.33", Port = "33", Country = "UK", UpTime = DateTime.Now, UserCount = 55 }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; var url = await CreateServerAsync(SI); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; Console.WriteLine($"Created at {url}"); } catch (HttpRequestException e) { Console.WriteLine("Fookking Error"); Console.WriteLine(e.Message); Console.WriteLine(e.InnerException.Message); } return(true); }
/// <summary> /// Отправка команды на удаленный компьютер /// </summary> /// <param name="message"></param> /// <param name="ServIn"></param> public void SendCommandToClient(string message, ServerInformation ServIn) { try { string IPadr = ServIn.IPAddres; string Portstr = ServIn.Port; TcpClient Client = new TcpClient(); int Port = Convert.ToInt32(Portstr); try { Client.Connect(IPadr, Port); string dat = "<sended_sign>" + message + "</sended_sign>"; NetworkStream stream = Client.GetStream(); try { Byte[] data = System.Text.Encoding.ASCII.GetBytes(dat); stream.Write(data, 0, data.Length); MessageBox.Show("Удаленный сервер : " + ServIn.Name + " " + ServIn.IPAddres + ":" + ServIn.Port + " " + message + "!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { MessageBox.Show("failed !" + ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } stream.Close(); Client.Close(); } catch { MessageBox.Show("Нет соединения с удаленным сервером!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information); } } catch { MessageBox.Show("Ip адрес или порт некорректны !", "Информация", MessageBoxButton.OK, MessageBoxImage.Information); } }
public Apple() { _severInfo = new ServerInformation { ServerStarted = DateTime.Now, ServerVersion = new Version("2.0.0"), Author = "Josh Hallow", Title = "Apple Server", Developers = new List <string> { "Josh Hallow" } }; _log = LogManager.GetLogger(typeof(Apple)); _log.Info("Apple server is loading."); _appleConfig = new AppleConfig("config.ini"); SocketSettings socketSettings = new SocketSettings { EndPoint = new IPEndPoint(IPAddress.Any, int.Parse(_appleConfig.GetConfigElement("game.socket.port"))), SocketBacklog = ushort.Parse(_appleConfig.GetConfigElement("game.socket.backlog")), _log = LogManager.GetLogger(typeof(SocketManager)) }; _socketManager = new SocketManager(socketSettings); _appleEncoding = new AppleEncoding(); _packetManager = new PacketManager(); _gameManager = new GameManager(); string interval = _appleConfig.GetConfigElement("console.timer.interval"); _consoleWorker = new ConsoleWorker(ushort.Parse(interval)); _consoleWorker.UpdateConsoleTitle(); _log.Info(_severInfo.Title + " is ready."); }
/// <summary> /// Prompts the user for all of the server information necessary. /// </summary> /// <returns>An object containing the collected information</returns> private static ServerInformation ReadServerInfo() { Console.Write("Server: "); var server = Console.ReadLine(); Console.Write("Port: "); var portString = Console.ReadLine(); int port; var successful = int.TryParse(portString, out port); if (!successful) { return(null); } var info = new ServerInformation { HostName = server, Port = port }; return(info); }
// GET: Carta public ActionResult Redactar() { ServerInformer serverInformer = new ServerInformer(); ServerInformation serverInformation = serverInformer.GetServerInformation(); ViewBag.fechaServidor = serverInformation.ServerDate; ViewBag.horaServidor = serverInformation.ServerHour; ViewBag.ipServidorPrivada = serverInformation.PrivateIpServer; ViewBag.ipServidorPublica = serverInformation.PublicIpServer; ViewBag.countryName = serverInformation.CountryName; ViewBag.regionName = serverInformation.RegionName; ViewBag.cityName = serverInformation.CityName; DataConnectionManager data = new DataConnectionManager(); List <Tratamiento> tratamientos = data.GetTratamientos(); List <Despedida> despedidas = data.GetDespedidas(); List <Cargo> cargos = data.GetCargos(); ViewBag.tratamientos = tratamientos; ViewBag.despedidas = despedidas; ViewBag.cargos = cargos; return(View()); }
public abstract Task Update(ServerInformation serverInformation, int updaterRef);
public abstract Task Delete(ServerInformation serverInformation, int deleterRef);
public IServerInformation Initialize(IConfiguration configuration) { var information = new ServerInformation(); information.Initialize(configuration); return information; }
public abstract Task Add(ServerInformation serverInformation, int adderRef);
public void Update() { // Recieve messages from the server. while ((_msgBuffer = _client.ReadMessage()) != null) { NetIncomingMessageType msgType = _msgBuffer.MessageType; switch (msgType) { case NetIncomingMessageType.StatusChanged: { NetConnectionStatus status = (NetConnectionStatus)_msgBuffer.ReadByte(); if (status == NetConnectionStatus.Disconnected) { string reason = _msgBuffer.ReadString(); switch (reason) { case "kicked": { _pbag.GameManager.SetErrorState(ErrorMsg.Kicked); break; } case "banned": { _pbag.GameManager.SetErrorState(ErrorMsg.Banned); break; } case "serverfull": { _pbag.GameManager.SetErrorState(ErrorMsg.ServerFull); break; } case "versionmismatch": { _pbag.GameManager.SetErrorState(ErrorMsg.VersionMismatch); break; } case "shutdown": { _pbag.GameManager.SetErrorState(ErrorMsg.ServerShutdown); break; } case "restart": { _pbag.GameManager.SetErrorState(ErrorMsg.ServerRestart); break; } case "exit": { //Todo need to find more info about this case in the disconnect switch break; } default: { _pbag.GameManager.Temperrormsg(reason); //Pbag.GameManager.SetErrorState(ErrorMsg.Unkown); break; } } } break; } case NetIncomingMessageType.DiscoveryResponse: { string name = _msgBuffer.ReadString(); int playercount = _msgBuffer.ReadInt32(); int playermax = _msgBuffer.ReadInt32(); bool lan = _msgBuffer.ReadBoolean(); string ip = _msgBuffer.SenderEndpoint.Address.ToString(); ServerInformation newserver = new ServerInformation(name,ip,playercount,playermax,lan); _pbag.GameManager.AddServer(newserver); break; } case NetIncomingMessageType.ConnectionApproval: { break; } case NetIncomingMessageType.Data: { PacketType dataType = (PacketType)_msgBuffer.ReadByte(); switch (dataType) { case PacketType.WorldMapSize: { _pbag.WorldManager.Mapsize = _msgBuffer.ReadInt32(); _pbag.WorldManager.Start(); break; } case PacketType.PlayerInitialUpdate: { _pbag.Player.Myid = _msgBuffer.ReadInt32(); _pbag.Player.Name = _msgBuffer.ReadString(); _pbag.Player.Position = _msgBuffer.ReadVector3(); break; } case PacketType.PlayerJoined: { ClientPlayer dummy = new ClientPlayer(_pbag.GameManager.Conmanager); dummy.Id = _msgBuffer.ReadInt32(); dummy.Name = _msgBuffer.ReadString(); dummy.Position = _msgBuffer.ReadVector3(); dummy.Heading = _msgBuffer.ReadVector3(); _pbag.WorldManager.Playerlist.Add(dummy.Id, dummy); break; } case PacketType.PlayerLeft: { int id = _msgBuffer.ReadInt32(); _pbag.WorldManager.Playerlist.Remove(id); break; } case PacketType.PlayerMovementUpdate: { int id = _msgBuffer.ReadInt32(); if (_pbag.WorldManager.Playerlist.ContainsKey(id)) { _pbag.WorldManager.Playerlist[id].Position = _msgBuffer.ReadVector3(); } break; } case PacketType.PlayerNameSet: { int id = _msgBuffer.ReadInt32(); //Lets see if its my id or someones else id if (_pbag.Player.Myid == id) { _pbag.Player.Name = _msgBuffer.ReadString(); } else { //Then its someones else its id if (_pbag.WorldManager.Playerlist.ContainsKey(id)) { _pbag.WorldManager.Playerlist[id].Position = _msgBuffer.ReadVector3(); } } break; } default: { break; } } } break; } } }
// private methods private void LookupServerInformation(MongoConnection connection) { IsMasterResult isMasterResult = null; bool ok = false; try { var isMasterCommand = new CommandDocument("ismaster", 1); var tempResult = connection.RunCommand("admin", QueryFlags.SlaveOk, isMasterCommand, false); isMasterResult = new IsMasterResult(); isMasterResult.Initialize(isMasterCommand, tempResult.Response); if (!isMasterResult.Ok) { throw new MongoCommandException(isMasterResult); } MongoServerBuildInfo buildInfo; var buildInfoCommand = new CommandDocument("buildinfo", 1); var buildInfoResult = connection.RunCommand("admin", QueryFlags.SlaveOk, buildInfoCommand, false); if (buildInfoResult.Ok) { buildInfo = MongoServerBuildInfo.FromCommandResult(buildInfoResult); } else { // short term fix: if buildInfo fails due to auth we don't know the server version; see CSHARP-324 if (buildInfoResult.ErrorMessage != "need to login") { throw new MongoCommandException(buildInfoResult); } buildInfo = null; } ReplicaSetInformation replicaSetInformation = null; MongoServerInstanceType instanceType = MongoServerInstanceType.StandAlone; if (isMasterResult.ReplicaSetName != null) { var peers = isMasterResult.Hosts.Concat(isMasterResult.Passives).Concat(isMasterResult.Arbiters).ToList(); replicaSetInformation = new ReplicaSetInformation(isMasterResult.ReplicaSetName, isMasterResult.Primary, peers, isMasterResult.Tags); instanceType = MongoServerInstanceType.ReplicaSetMember; } else if (isMasterResult.Message != null && isMasterResult.Message == "isdbgrid") { instanceType = MongoServerInstanceType.ShardRouter; } var newServerInfo = new ServerInformation { BuildInfo = buildInfo, InstanceType = instanceType, IsArbiter = isMasterResult.IsArbiterOnly, IsMasterResult = isMasterResult, IsPassive = isMasterResult.IsPassive, IsPrimary = isMasterResult.IsPrimary, IsSecondary = isMasterResult.IsSecondary, MaxDocumentSize = isMasterResult.MaxBsonObjectSize, MaxMessageLength = isMasterResult.MaxMessageLength, ReplicaSetInformation = replicaSetInformation }; MongoServerState currentState; lock (_serverInstanceLock) { currentState = _state; } SetState(currentState, newServerInfo); ok = true; } finally { if (!ok) { ServerInformation currentServerInfo; lock (_serverInstanceLock) { currentServerInfo = _serverInfo; } // keep the current instance type, build info, and replica set info // as these aren't relevent to state and are likely still correct. var newServerInfo = new ServerInformation { BuildInfo = currentServerInfo.BuildInfo, InstanceType = currentServerInfo.InstanceType, IsArbiter = false, IsMasterResult = isMasterResult, IsPassive = false, IsPrimary = false, IsSecondary = false, MaxDocumentSize = currentServerInfo.MaxDocumentSize, MaxMessageLength = currentServerInfo.MaxMessageLength, ReplicaSetInformation = currentServerInfo.ReplicaSetInformation }; SetState(MongoServerState.Disconnected, newServerInfo); } } }
public bool IsDifferentFrom(ServerInformation other) { if (InstanceType != other.InstanceType) { return true; } if (IsPrimary != other.IsPrimary) { return true; } if (IsSecondary != other.IsSecondary) { return true; } if (IsPassive != other.IsPassive) { return true; } if (IsArbiter != other.IsArbiter) { return true; } if (MaxDocumentSize != other.MaxDocumentSize) { return true; } if (MaxMessageLength != other.MaxMessageLength) { return true; } if ((ReplicaSetInformation == null && other.ReplicaSetInformation != null) || (ReplicaSetInformation != other.ReplicaSetInformation)) { return true; } return false; }
public void RemoveServer(ServerInformation server) { _servers.Remove(server.GetTag()); _serversbox.Items.Remove(server.GetTag()); }
public void AddServer(ServerInformation server) { _serverbrowsingstate.AddServer(server); }
/// <remarks>This method must be called outside of a lock.</remarks> private void SetState(MongoServerState newState, ServerInformation newServerInfo) { bool raiseChangedEvent = false; lock (_serverInstanceLock) { if (_state != newState) { _state = newState; raiseChangedEvent = true; } if (newState == MongoServerState.Disconnected) { _connectionPool.Clear(); } if (_serverInfo != newServerInfo && _serverInfo.IsDifferentFrom(newServerInfo)) { _serverInfo = newServerInfo; raiseChangedEvent = true; } } if (raiseChangedEvent) { OnStateChanged(); } }
public Game() { one = 1; map = new Map(); performanceinfo = new DictionaryStringString(); AudioEnabled = true; AutoJumpEnabled = false; playerPositionSpawnX = 15 + one / 2; playerPositionSpawnY = 64; playerPositionSpawnZ = 15 + one / 2; TextureId = new int[MaxBlockTypes][]; for (int i = 0; i < MaxBlockTypes; i++) { TextureId[i] = new int[6]; } TextureIdForInventory = new int[MaxBlockTypes]; language = new Language(); lastplacedblockX = -1; lastplacedblockY = -1; lastplacedblockZ = -1; mLightLevels = new float[16]; sunlight_ = 15; mvMatrix = new StackMatrix4(); pMatrix = new StackMatrix4(); mvMatrix.Push(Mat4.Create()); pMatrix.Push(Mat4.Create()); whitetexture = -1; cachedTextTexturesMax = 1024; cachedTextTextures = new CachedTextTexture[cachedTextTexturesMax]; for (int i = 0; i < cachedTextTexturesMax; i++) { cachedTextTextures[i] = null; } packetLen = new IntRef(); ENABLE_DRAW2D = true; AllowFreemove = true; enableCameraControl = true; textures = new DictionaryStringInt1024(); ServerInfo = new ServerInformation(); menustate = new MenuState(); mouseleftclick = false; mouseleftdeclick = false; wasmouseleft = false; mouserightclick = false; mouserightdeclick = false; wasmouseright = false; ENABLE_LAG = 0; znear = one / 10; CameraMatrix = new GetCameraMatrix(); ENABLE_ZFAR = true; TotalAmmo = new int[GlobalVar.MAX_BLOCKTYPES]; LoadedAmmo = new int[GlobalVar.MAX_BLOCKTYPES]; AllowedFontsCount = 1; AllowedFonts = new string[AllowedFontsCount]; AllowedFonts[0] = "Verdana"; fov = Game.GetPi() / 3; cameratype = CameraType.Fpp; ENABLE_TPP_VIEW = false; basemovespeed = 5; movespeed = 5; RadiusWhenMoving = one * 3 / 10; playervelocity = new Vector3Ref(); LocalPlayerId = -1; dialogs = new VisibleDialog[512]; dialogsCount = 512; blockHealth = new DictionaryVector3Float(); playertexturedefault = -1; a = new AnimationState(); constRotationSpeed = one * 180 / 20; modmanager = new ClientModManager1(); particleEffectBlockBreak = new ModDrawParticleEffectBlockBreak(); PICK_DISTANCE = 4.1f; selectedmodelid = -1; grenadetime = 3; rotationspeed = one * 15 / 100; entities = new Entity[entitiesMax]; for (int i = 0; i < entitiesMax; i++) { entities[i] = null; } entitiesCount = 512; PlayerPushDistance = 2; const int KeysMax = 256; keyboardState = new bool[KeysMax]; for (int i = 0; i < KeysMax; i++) { keyboardState[i] = false; } keyboardStateRaw = new bool[KeysMax]; for (int i = 0; i < KeysMax; i++) { keyboardStateRaw[i] = false; } overheadcameradistance = 10; tppcameradistance = 3; TPP_CAMERA_DISTANCE_MIN = 1; TPP_CAMERA_DISTANCE_MAX = 10; options = new OptionsCi(); overheadcameraK = new Kamera(); fillAreaLimit = 200; speculativeCount = 0; speculative = new Speculative[speculativeMax]; typinglog = new string[1024 * 16]; typinglogCount = 0; NewBlockTypes = new Packet_BlockType[GlobalVar.MAX_BLOCKTYPES]; localplayeranim = new AnimationState(); localplayeranimationhint = new AnimationHint(); enable_move = true; handTexture = -1; modelViewInverted = new float[16]; GLScaleTempVec3 = Vec3.Create(); GLRotateTempVec3 = Vec3.Create(); GLTranslateTempVec3 = Vec3.Create(); identityMatrix = Mat4.Identity_(Mat4.Create()); Set3dProjectionTempMat4 = Mat4.Create(); getAsset = new string[1024 * 2]; PlayerStats = new Packet_ServerPlayerStats(); mLightLevels = new float[16]; for (int i = 0; i < 16; i++) { mLightLevels[i] = one * i / 15; } soundnow = new BoolRef(); camera = Mat4.Create(); packetHandlers = new ClientPacketHandler[256]; player = new Entity(); player.position = new EntityPosition_(); currentlyAttackedEntity = -1; ChatLinesMax = 1; ChatLines = new Chatline[ChatLinesMax]; ChatLineLength = 64; audio = new AudioControl(); CameraEyeX = -1; CameraEyeY = -1; CameraEyeZ = -1; controls = new Controls(); movedz = 0; taskScheduler = new TaskScheduler(); commitActions = ListAction.Create(16 * 1024); constWallDistance = 0.3f; mouseSmoothing = true; }
private void SetState(MongoServerState state, ServerInformation serverInfo) { var currentServerInfo = Interlocked.CompareExchange(ref _stateInfo, null, null); bool raiseChangedEvent = false; lock (_stateLock) { if (_state != state) { _state = state; raiseChangedEvent = true; } if (state == MongoServerState.Disconnected) { _connectionPool.Clear(); } if (currentServerInfo != serverInfo && currentServerInfo.IsDifferentFrom(serverInfo)) { Interlocked.Exchange(ref _stateInfo, serverInfo); raiseChangedEvent = true; } } if (raiseChangedEvent) { OnStateChanged(); } }
/// <summary> /// Writes the server information to the connection /// </summary> /// <param name="si"></param> public void Write(ServerInformation si) { byte[] version = BitConverter.GetBytes(si.version); byte[] flags = BitConverter.GetBytes(si.flags); Write(version); Write(flags); }
private void HandleDelete(ServerInformation server) { this.storage.Servers.Remove(server); }
public void AddServer(ServerInformation server) { _servers.Add(server.GetTag(), server); _serversbox.Items.Add(server.GetTag()); }
public void RemoveServer(ServerInformation server) { _serverbrowsingstate.RemoveServer(server); }