void t_Elapsed(object sender, ElapsedEventArgs e) { var level = (LogEventLevel) new Random().Next(0, 5); switch (level) { case LogEventLevel.Verbose: Composable.GetExport <IXLogger>().Verbose("This is a Serilog.Sinks.XSockets test with level {0}", level); break; case LogEventLevel.Debug: Composable.GetExport <IXLogger>().Debug("This is a Serilog.Sinks.XSockets test with level {0}", level); break; case LogEventLevel.Information: Composable.GetExport <IXLogger>().Information("This is a Serilog.Sinks.XSockets test with level {0}", level); break; case LogEventLevel.Warning: Composable.GetExport <IXLogger>().Warning("This is a Serilog.Sinks.XSockets test with level {0}", level); break; case LogEventLevel.Error: Composable.GetExport <IXLogger>().Error("This is a Serilog.Sinks.XSockets test with level {0}", level); break; case LogEventLevel.Fatal: Composable.GetExport <IXLogger>().Fatal("This is a Serilog.Sinks.XSockets test with level {0}", level); break; } }
public override async Task HandShake(byte[] ar) { var rawHandshake = Encoding.UTF8.GetString(ar, 0, ar.Length); var identifiedProtocol = GetProtocolFromHandshake(ar); if (identifiedProtocol != null && identifiedProtocol is HyperTextTransferProtocol) { //Get the instance of the identified protocol var http = (HyperTextTransferProtocol)await identifiedProtocol.Resolve(ar, Transport, Configuration); var path = http.Handshake.Split(' '); if (path[0] == "GET" && path[1] == "/") { Composable.GetExport <IXLogger>().Information("ProtocolHandshakeHandler - Handshake OK: {h}", rawHandshake); var success = await Transport.Send(NOCONTENT); await http.Disconnect(false); } else { await base.HandShake(ar); } return; } else { await base.HandShake(ar); } }
public static void StartOnAzure(this IXSocketServerContainer container) { //Configurations var configs = new List <IConfigurationSetting>(); var uriStr = RoleEnvironment.GetConfigurationSettingValue("uri"); var origins = new HashSet <string>(RoleEnvironment.GetConfigurationSettingValue("origin").Split(',').ToList()); var instanceEndpoints = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.Values.Where(p => p.Protocol.Equals("tcp")); //Create endpoints foreach (var endpoint in instanceEndpoints) { var uri = new Uri(uriStr.Replace("port", endpoint.IPEndpoint.Port.ToString(CultureInfo.InvariantCulture))); configs.Add(new ConfigurationSetting(uri, origins) { Endpoint = endpoint.IPEndpoint }); Composable.GetExport <IXLogger>().Information("Endpoint {@endpoint}", endpoint); } if (!configs.Any()) { Composable.GetExport <IXLogger>().Fatal("Could not find a TCP endpoint, check your configuration"); return; } //Start server with endpoints container.Start(false, configurationSettings: configs); }
public override async Task <byte[]> GetHostResponse() { try { var connectMessage = MqttHelpers.Parse((byte)MqttProtocolVersion.Version_3_1_1, this.RawHandshake); //var connectMessage = MqttMsgConnect.Parse((byte)MqttProtocolVersion.Version_3_1_1, this.RawHandshake); this.ConnectionContext.Environment = new Dictionary <string, object>(); this.ConnectionContext.Environment.Add("mqttclient", connectMessage); ConnectionContext.User = _authenticationPipeline.GetPrincipal(this); Broker.MqttOpen(connectMessage); await Broker.Open(); return(new byte[0]); } catch (Exception ex) { // 3.1.4.2 - The Server MUST validate that the CONNECT Packet conforms to section 3.1 // and close the Network Connection without sending a CONNACK if it does not conform Composable.GetExport <IXLogger>().Error(ex, "MQTT CONNECT FAILED"); await Disconnect(false); return(new byte[0]); } }
static void Main(string[] args) { using (var container = Composable.GetExport <IXSocketServerContainer>()) { container.Start(); Console.ReadLine(); } }
public override async Task OnMessage(IMessage message) { if (Debugger.IsAttached) { Composable.GetExport <IXLogger>().Verbose("MyController:OnMessage {@m}", message); } await this.InvokeToAll(message); }
public MqttProtocol() { Broker = new MqttController { ProtocolInstance = this, }; ProtocolProxy = new MqttProtocolProxy(); _authenticationPipeline = Composable.GetExport <IXSocketAuthenticationPipeline>(); }
public StorageObject(string partitiokKey, string rowKey, object o) { this.PartitionKey = partitiokKey; this.RowKey = rowKey; var t = o.GetType(); this.Type = string.Format("{0}, {1}", t.FullName, Assembly.GetAssembly(t).GetName().Name); this.JSON = Composable.GetExport <IXSocketJsonSerializer>().SerializeToString(o, o.GetType()); }
static void Main(string[] args) { using (WebApp.Start <Startup>("http://localhost:12345")) { Composable.GetExport <IXLogger>().Information("All files under Sample/Web should have the property 'Copy to output directory' set to 'Copy always'"); Console.WriteLine("Navigate to: http://localhost:12345/Sample/Web/Stockticker.html"); Console.ReadLine(); } }
/// <summary> /// The handshake should contain Sec-WebSocket-Version:\13 /// The handshake should NOT contain any subprotocol /// </summary> /// <param name="handshake"></param> /// <returns></returns> public override async Task <bool> Match(IList <byte> handshake) { var s = Encoding.UTF8.GetString(handshake.ToArray()); Composable.GetExport <IXLogger>().Information(s); return (Regex.Match(s, @"(^Sec-WebSocket-Version:\s13)", RegexOptions.Multiline).Success && Regex.Match(s, @"(^Sec-WebSocket-Protocol:\sNative)", RegexOptions.Multiline).Success); }
public override bool OnStart() { bool result = base.OnStart(); //Get the server container _container = Composable.GetExport <IXSocketServerContainer>(); //Start in worker role _container.StartOnAzure(); return(result); }
static void Main(string[] args) { using (var container = Composable.GetExport <IXSocketServerContainer>()) { Composable.GetExport <IXSocketsScaleOut>().AddScaleOut("ws://127.0.0.1:4503"); Composable.GetExport <IXSocketsScaleOut>().AddScaleOut("ws://127.0.0.1:4504"); Composable.GetExport <IXSocketsScaleOut>().AddScaleOut("ws://127.0.0.1:4505"); container.Start(); Console.ReadLine(); } }
protected void Application_Start() { // Start the MVC->XSockets bridge _container = Composable.GetExport <IXSocketsRelayContainer>(); _container.Start(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
public MqttManager() { // create managers (publisher, subscriber, session and UAC) this.subscriberManager = new MqttSubscriberManager(); this.sessionManager = new MqttSessionManager(); this.publisherManager = new MqttPublisherManager(this.subscriberManager, this.sessionManager); this.uacManager = new MqttUacManager(); this.clients = new MqttClientCollection(); mqttBridge = Composable.GetExport <IMqttBridge>(); }
public override bool OnStart() { bool result = base.OnStart(); // Use the XSockets.NET Plugin Framwork to get an IXSocketServerContainer _container = Composable.GetExport <IXSocketServerContainer>(); //Start server by using extension (see ConfigurationHelper) _container.StartOnAzure(); return(result); }
/// <summary> /// Convert the incoming data to an IMessage of with correct type (text/binary) /// </summary> /// <param name="payload"></param> /// <param name="messageType"></param> /// <returns></returns> public override IMessage OnIncomingFrame(IEnumerable <byte> payload, MessageType messageType) { Composable.GetExport <IXLogger>().Information("Native Websockets {p}", Encoding.UTF8.GetString(payload.ToArray())); if (messageType == MessageType.Binary) { return(new Message(payload, "bar", "foo")); } else { return(new Message(Encoding.UTF8.GetString(payload.ToArray()), "bar", "foo")); } }
/// <summary> /// When the controller is openend by the client it sends back information about all the connected sensors. /// </summary> public override async Task OnOpened() { //Send back containerId so see if we are on different servers when scaling await this.Invoke(Composable.GetExport <IXSocketServerContainer>().ContainerId, "containerid"); //Default temp limit this.TempLimit = 10; //Find all sensors and get latest known value and name var sensors = this.FindOn <Sensor>().Select(p => p.SensorInfo); //Send back sensor information await this.Invoke(sensors, "sensors"); }
/// <summary> /// Log the incomming data and send it back to the caller only /// </summary> /// <param name="model"></param> public void LogTest(SomeModel model) { try { //Get the logger and write with level information Composable.GetExport <IXLogger>().Information("LogTest: {@model}", model); //And... throw... throw new Exception("Ohh crap!"); } catch (Exception ex) { Composable.GetExport <IXLogger>().Error("LogTest: {@ex}", ex); } }
/// <summary> /// When a client connects create a new PeerConnection and send the information the the client /// </summary> public override async Task OnOpened() { var groupId = Guid.NewGuid(); if (this.HasParameterKey("grouppeer")) { var p = this.GetParameter("grouppeer"); groupId = Guid.Parse(p); this.GroupId = groupId; } // Get the context from a parameter if it exists var context = Guid.NewGuid(); if (this.HasParameterKey("ctx")) { var p = this.GetParameter("ctx"); context = Guid.Parse(p); this.ContextId = context; } IPresence user = new Presence { Online = true, UserName = "******", GroupId = groupId, Context = context, Id = this.PersistentId }; //Update user if (XSockets.Core.Utility.Storage.Repository <Guid, IPresence> .ContainsKey(this.PersistentId)) { user = XSockets.Core.Utility.Storage.Repository <Guid, IPresence> .GetById(user.Id); if (this.HasParameterKey("username")) { user.UserName = this.GetParameter("username"); } } SavePresence(user); var others = XSockets.Core.Utility.Storage.Repository <Guid, IPresence> .Find(p => p.Id != user.Id); Composable.GetExport <IXLogger>().Information("Others {@a}", others); await this.Invoke(others, "allusers"); Peer = new PeerConnection { Context = context, PeerId = ConnectionId, GroupId = groupId }; await this.Invoke(Peer, Events.Context.Created); }
/// <summary> /// When a client connects create a new PeerConnection and send the information the the client /// </summary> /// <param name="sender"></param> /// <param name="onClientConnectArgs"></param> private void _OnOpen(object sender, OnClientConnectArgs onClientConnectArgs) { IPresence user = new Presence { Online = true, UserName = "******", Id = this.PersistentId }; //Update user if (Core.Utility.Storage.Repository <Guid, IPresence> .ContainsKey(this.PersistentId)) { user = Core.Utility.Storage.Repository <Guid, IPresence> .GetById(user.Id); if (this.HasParameterKey("username")) { user.UserName = this.GetParameter("username"); } } SavePresence(user); var others = Core.Utility.Storage.Repository <Guid, IPresence> .Find(p => p.Id != user.Id); Composable.GetExport <IXLogger>().Information("Others {@a}", others); this.Invoke(others, "allusers"); // Get the context from a parameter if it exists var context = Guid.NewGuid(); if (this.HasParameterKey("ctx")) { var p = this.GetParameter("ctx"); context = Guid.Parse(p); } Peer = new PeerConnection { Context = context, PeerId = ConnectionId }; this.Invoke(Peer, Events.Context.Created); }
public void MqttOpen(MqttMsgConnect msg) { MqttClient = new MqttClient(this.ProtocolInstance.Transport.Socket); ((MqttManager)Composable.GetExport <IXSocketController>(typeof(MqttManager))).RegisterClient(this.MqttClient, msg); }
public static void Main(string[] args) { XmlConfigurator.Configure(); System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; Console.Title = string.Format("[{0}] D2MP Master", version); log.Info("Master server starting v." + version + "."); log.Info("Initializing database..."); log.Debug(Settings.Default.MongoURL); Mongo.Setup(); Task.Factory.StartNew(Mongo.UpdateOldMatchResults); log.Info("Caching mods..."); Mods.Mods.InitCache(); log.Info(Mods.Mods.ModCache.Count + " mods cached."); log.Info("Generating server addon list..."); ServerAddons.Init(Mods.Mods.ModCache.Values); log.Info("Initializing Amazon S3..."); S3 = new S3Manager(); log.Info("Initializing match result server..."); Uri[] urilist = null; { IList <Uri> uris = new List <Uri>(); #if DEBUG || DEV uris.Add(new Uri("http://127.0.0.1:" + Settings.Default.WebserverBind)); //uris.Add(new Uri("http://10.0.1.3:" + Settings.Default.WebserverBind)); #else //uris.Add(new Uri("http://net1.d2modd.in:" + Settings.Default.WebserverBind)); uris.Add(new Uri("http://" + Settings.Default.WebAddress + ":" + Settings.Default.WebserverBind)); #endif urilist = uris.ToArray(); } foreach (var uri in urilist) { log.Debug(uri); } var config = new HostConfiguration(); using (var nancyServer = new NancyHost(config, urilist)) { nancyServer.Start(); log.Info("Initializing xsockets..."); Console.CancelKeyPress += delegate { shutdown = true; }; using (var server = Composable.GetExport <IXSocketServerContainer>()) { server.StartServers(); Mods.Mods.StartUpdateTimer(); Lobbies.LobbyManager.Start(); log.Info("Server running!"); while (!shutdown) { Thread.Sleep(100); } BrowserController.cts.Cancel(); ClientController.cts.Cancel(); ServerController.cts.Cancel(); Lobbies.LobbyManager.Stop(); Mods.Mods.StopUpdateTimer(); server.StopServers(); } nancyServer.Stop(); } log.Info("Done, shutting down..."); //wserver.Stop(); }
protected void Application_Start() { Container container = new Container(); IoC.Configure(container); //RouteTable.Routes.MapHubs(); //assign instrumentation key to appinsights Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["iKey"]; ControllerBuilder.Current.SetControllerFactory(typeof(SmarttouchControllerFactory)); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //ControllerBuilder.Current.SetControllerFactory(typeof(SmarttouchControllerFactory)); InitializeAutoMapper.Initialize(); //GlobalConfiguration.Configuration.EnsureInitialized(); HttpContext.Current.Application["image_hostedpath"] = ConfigurationManager.AppSettings["IMAGE_HOSTING_SERVICE_URL"]; HttpContext.Current.Application["webservice_url"] = ConfigurationManager.AppSettings["WEBSERVICE_URL"]; Logger.Current.CreateRollingFlatFileListener(EventLevel.Verbose, ConfigurationManager.AppSettings["WEBAPP_LOG_FILE_PATH"], 2048); ExceptionHandler.Current.AddDefaultLogAndRethrowPolicy(); ExceptionHandler.Current.AddDefaultLogOnlyPolicy(); i18n.LocalizedApplication.Current.DefaultLanguage = "en"; i18n.UrlLocalizer.UrlLocalizationScheme = i18n.UrlLocalizationScheme.Void; var defaultJsonFactory = ValueProviderFactories.Factories.OfType <JsonValueProviderFactory>().FirstOrDefault(); var index = ValueProviderFactories.Factories.IndexOf(defaultJsonFactory); ValueProviderFactories.Factories.Remove(defaultJsonFactory); ValueProviderFactories.Factories.Insert(index, new SmartTouchJsonValueProviderFactory()); bool isHttpsMode = false; string httpsMode = System.Configuration.ConfigurationManager.AppSettings["IsHttpsMode"]; bool.TryParse(httpsMode, out isHttpsMode); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); var masterAccountDns = ConfigurationManager.AppSettings["MASTER_ACCOUNT_DNS"]; if (masterAccountDns.Equals("localhost")) { using (var socketServerContainer = Composable.GetExport <IXSocketServerContainer>()) { socketServerContainer.StartServers(); } } else { using (var socketServerContainer = Composable.GetExport <IXSocketServerContainer>()) { IList <IConfigurationSetting> configurationSettings = new List <IConfigurationSetting>(); //string uri = string.Empty; IConfigurationSetting configSetting = null; Uri uri = null; if (isHttpsMode) { string sslKey = System.Configuration.ConfigurationManager.AppSettings["SSLSerialNumber"]; uri = new Uri("wss://" + ConfigurationManager.AppSettings["MASTER_ACCOUNT_DNS"] + ":" + ConfigurationManager.AppSettings["WEBSOCKET_PORT"]); X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var certificate = store.Certificates.Find(X509FindType.FindBySerialNumber, sslKey, false).OfType <X509Certificate2>().FirstOrDefault(); if (certificate != null) { Logger.Current.Informational("certificate found"); configSetting = new ConfigurationSetting { Port = uri.Port, Origin = new HashSet <string>() { "*" }, Uri = uri, Certificate = certificate }; Logger.Current.Informational("Configured was mode for websockets."); } else { Logger.Current.Informational("certificate not found"); foreach (X509Certificate2 objCert in store.Certificates) { string serialNumber = objCert.SerialNumber.Trim().ToString().ToUpper(); Logger.Current.Verbose("Certificate name" + objCert.FriendlyName + " Store serial number:" + objCert.SerialNumber.Trim()); string orgSerialNumber = sslKey.Trim().ToString().ToUpper(); if (String.Equals(serialNumber, orgSerialNumber, StringComparison.InvariantCulture)) { certificate = objCert; } } if (certificate != null) { Logger.Current.Informational("Certificate found."); configSetting = new ConfigurationSetting { Port = uri.Port, Origin = new HashSet <string>() { "*" }, Uri = uri, Certificate = certificate }; Logger.Current.Informational("Configured wss mode for websockets."); } else { Logger.Current.Informational("Certificate not found. Could not set wss for the application."); } } } else { uri = new Uri("ws://" + ConfigurationManager.AppSettings["MASTER_ACCOUNT_DNS"] + ":" + ConfigurationManager.AppSettings["WEBSOCKET_PORT"]); configSetting = new ConfigurationSetting(uri); Logger.Current.Informational("Configured ws mode for websockets."); } configurationSettings.Add(configSetting); socketServerContainer.StartServers(withInterceptors: true, configurationSettings: configurationSettings); } } }
public override async Task <IMessage> OnOutgoingMessage(IXSocketController controller, IMessage e) { Composable.GetExport <IXLogger>().Information("Outgoing data: {@m}", e); return(await base.OnOutgoingMessage(controller, e)); }
public override async Task OnIncomingMessage(IXSocketController controller, IMessage e) { Composable.GetExport <IXLogger>().Information("Incoming data: {@m}", e); await base.OnIncomingMessage(controller, e); }
public void Configuration(IAppBuilder app) { container = Composable.GetExport <IXSocketServerContainer>(); container.Start(); }
public object Deserialize() { return(Composable.GetExport <IXSocketJsonSerializer>().DeserializeFromString(this.JSON, System.Type.GetType(Type))); }
public override void OnIncomingMessage(IXSocketController controller, IMessage e) { Composable.GetExport <IXLogger>().Debug("Incoming data: {@m}", e); base.OnIncomingMessage(controller, e); }
public override IMessage OnOutgoingMessage(IXSocketController controller, IMessage e) { Composable.GetExport <IXLogger>().Debug("Outgoing data: {@m}", e); return(base.OnOutgoingMessage(controller, e)); }
public StupidProtocolProxy() { JsonSerializer = Composable.GetExport <IXSocketJsonSerializer>(); }