当前位置: 首页>>代码示例>>C#>>正文


C# HttpServer.AddWebSocketService方法代码示例

本文整理汇总了C#中HttpServer.AddWebSocketService方法的典型用法代码示例。如果您正苦于以下问题:C# HttpServer.AddWebSocketService方法的具体用法?C# HttpServer.AddWebSocketService怎么用?C# HttpServer.AddWebSocketService使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HttpServer的用法示例。


在下文中一共展示了HttpServer.AddWebSocketService方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        public static void Main(string [] args)
        {
            _httpsv = new HttpServer (4649);
              //_httpsv = new HttpServer (4649, true);
              #if DEBUG
              _httpsv.Log.Level = LogLevel.TRACE;
              #endif
              _httpsv.RootPath = ConfigurationManager.AppSettings ["RootPath"];
              //var certFile = ConfigurationManager.AppSettings ["ServerCertFile"];
              //var password = ConfigurationManager.AppSettings ["CertFilePassword"];
              //_httpsv.Certificate = new X509Certificate2 (certFile, password);
              //_httpsv.KeepClean = false;
              _httpsv.AddWebSocketService<Echo> ("/Echo");
              _httpsv.AddWebSocketService<Chat> ("/Chat");

              _httpsv.OnGet += (sender, e) =>
              {
            onGet (e);
              };

              _httpsv.Start ();
              if (_httpsv.IsListening)
              {
            Console.WriteLine ("HTTP Server listening on port: {0} service path:", _httpsv.Port);
            foreach (var path in _httpsv.WebSocketServices.ServicePaths)
              Console.WriteLine ("  {0}", path);

            Console.WriteLine ();
              }

              Console.WriteLine ("Press Enter key to stop the server...");
              Console.ReadLine ();

              _httpsv.Stop ();
        }
开发者ID:KingKiller,项目名称:websocket-sharp,代码行数:35,代码来源:Program.cs

示例2: Main

        public static void Main(string[] args)
        {
            _httpsv = new HttpServer(4649);
              //_httpsv.Sweeping = false;
              _httpsv.AddWebSocketService<Echo>("/Echo");
              _httpsv.AddWebSocketService<Chat>("/Chat");

              _httpsv.OnGet += (sender, e) =>
              {
            onGet(e);
              };

              _httpsv.OnError += (sender, e) =>
              {
            Console.WriteLine(e.Message);
              };

              _httpsv.Start();
              Console.WriteLine("HTTP Server listening on port: {0} service path:", _httpsv.Port);
              foreach (var path in _httpsv.ServicePaths)
            Console.WriteLine("  {0}", path);
              Console.WriteLine();

              Console.WriteLine("Press any key to stop server...");
              Console.ReadLine();

              _httpsv.Stop();
        }
开发者ID:rje,项目名称:websocket-sharp,代码行数:28,代码来源:Program.cs

示例3: Main

        public static void Main(string [] args)
        {
            _httpsv = new HttpServer (4649);
              #if DEBUG
              _httpsv.Log.Level = LogLevel.TRACE;
              #endif
              _httpsv.RootPath = ConfigurationManager.AppSettings ["RootPath"];
              //_httpsv.KeepClean = false;
              _httpsv.AddWebSocketService<Echo> ("/Echo");
              _httpsv.AddWebSocketService<Chat> ("/Chat");

              _httpsv.OnGet += (sender, e) =>
              {
            onGet (e);
              };

              _httpsv.OnError += (sender, e) =>
              {
            Console.WriteLine (e.Message);
              };

              _httpsv.Start ();
              Console.WriteLine ("HTTP Server listening on port: {0} service path:", _httpsv.Port);
              foreach (var path in _httpsv.ServicePaths)
            Console.WriteLine ("  {0}", path);
              Console.WriteLine ();

              Console.WriteLine ("Press enter key to stop the server...");
              Console.ReadLine ();

              _httpsv.Stop ();
        }
开发者ID:vnisor,项目名称:websocket-sharp,代码行数:32,代码来源:Program.cs

示例4: OnStart

 protected override void OnStart(string[] args)
 {
     _sv = new HttpServer(3128);
       _sv.Log.Output=WsLog;
       _sv.RootPath=Path.GetFullPath(Path.GetFullPath("../htdocs"));
       _sv.OnGet+=OnGet;
       _sv.AddWebSocketService<ApiV03>("/api/v03");
       _sv.Start();
       if(_sv.IsListening) {
     Log.Info("HttpServer started on {0}:{1} ", Environment.MachineName, _sv.Port.ToString());
       } else {
     Log.Error("HttpServer start failed");
       }
 }
开发者ID:Wassili-Hense,项目名称:era,代码行数:14,代码来源:era_svc.cs

示例5: Awake

 void Awake()
 {
     var port = 12002;
     var addr = "localhost";
     var fullUrl = addr + ":" + port;
     httpsv = new HttpServer("http://" + fullUrl);
     httpsv.RootPath = "./htmlcontents"; // TODO: まともなパスに書き換える
     string[] fs = System.IO.Directory.GetFiles(@httpsv.RootPath, "*");
     Debug.Log("current path:" + fs[0]);
     httpsv.Log.Level = LogLevel.Trace;
     httpsv.OnGet += (sender, e) => {
         var req = e.Request;
         var res = e.Response;
         var path = req.RawUrl;
         Debug.Log("http request:" + req);
         if (path == "/") path += "index.html";
         var content = httpsv.GetFile(path);
         if (content == null) {
             res.StatusCode = (int) HttpStatusCode.NotFound;
             res.WriteContent(
                 System.Text.Encoding.UTF8.GetBytes(
                 "File Not Found"));
             return;
         }
         if (path.EndsWith(".html")) {
             res.ContentType = "text/html";
             res.ContentEncoding = Encoding.UTF8;
         }
         res.WriteContent(content);
     };
     httpsv.WaitTime = TimeSpan.FromSeconds(2);
     httpsv.AddWebSocketService<MyService>("/MyService",() => {
         var service = new MyService(recognizedVoices);
         return service;
     });
     httpsv.Start();
     Debug.Log("http server started with " + fullUrl);
 }
开发者ID:kiripon,项目名称:webSocketSharpTest,代码行数:38,代码来源:chromeVoiceRecog.cs

示例6: Main

        public static void Main(string[] args)
        {
            /* Create a new instance of the HttpServer class.
               *
               * If you would like to provide the secure connection, you should create the instance with
               * the 'secure' parameter set to true, or the https scheme HTTP URL.
               */
              var httpsv = new HttpServer (4649);
              //var httpsv = new HttpServer (5963, true);
              //var httpsv = new HttpServer (System.Net.IPAddress.Parse ("127.0.0.1"), 4649);
              //var httpsv = new HttpServer (System.Net.IPAddress.Parse ("127.0.0.1"), 5963, true);
              //var httpsv = new HttpServer ("http://localhost:4649");
              //var httpsv = new HttpServer ("https://localhost:5963");
            #if DEBUG
              // To change the logging level.
              httpsv.Log.Level = LogLevel.Trace;

              // To change the wait time for the response to the WebSocket Ping or Close.
              httpsv.WaitTime = TimeSpan.FromSeconds (2);
            #endif
              /* To provide the secure connection.
              var cert = ConfigurationManager.AppSettings["ServerCertFile"];
              var passwd = ConfigurationManager.AppSettings["CertFilePassword"];
              httpsv.SslConfiguration.ServerCertificate = new X509Certificate2 (cert, passwd);
               */

              /* To provide the HTTP Authentication (Basic/Digest).
              httpsv.AuthenticationSchemes = AuthenticationSchemes.Basic;
              httpsv.Realm = "WebSocket Test";
              httpsv.UserCredentialsFinder = id => {
            var name = id.Name;

            // Return user name, password, and roles.
            return name == "nobita"
               ? new NetworkCredential (name, "password", "gunfighter")
               : null; // If the user credentials aren't found.
              };
               */

              // To set the document root path.
              httpsv.RootPath = ConfigurationManager.AppSettings["RootPath"];

              // To set the HTTP GET method event.
              httpsv.OnGet += (sender, e) => {
            var req = e.Request;
            var res = e.Response;

            var path = req.RawUrl;
            if (path == "/")
              path += "index.html";

            var content = httpsv.GetFile (path);
            if (content == null) {
              res.StatusCode = (int) HttpStatusCode.NotFound;
              return;
            }

            if (path.EndsWith (".html")) {
              res.ContentType = "text/html";
              res.ContentEncoding = Encoding.UTF8;
            }

            res.WriteContent (content);
              };

              // Not to remove the inactive WebSocket sessions periodically.
              //httpsv.KeepClean = false;

              // To resolve to wait for socket in TIME_WAIT state.
              //httpsv.ReuseAddress = true;

              // Add the WebSocket services.
              httpsv.AddWebSocketService<Echo> ("/Echo");
              httpsv.AddWebSocketService<Chat> ("/Chat");

              /* Add the WebSocket service with initializing.
              httpsv.AddWebSocketService<Chat> (
            "/Chat",
            () => new Chat ("Anon#") {
              Protocol = "chat",
              // To ignore the Sec-WebSocket-Extensions header.
              IgnoreExtensions = true,
              // To validate the Origin header.
              OriginValidator = val => {
            // Check the value of the Origin header, and return true if valid.
            Uri origin;
            return !val.IsNullOrEmpty () &&
                   Uri.TryCreate (val, UriKind.Absolute, out origin) &&
                   origin.Host == "localhost";
              },
              // To validate the Cookies.
              CookiesValidator = (req, res) => {
            // Check the Cookies in 'req', and set the Cookies to send to the client with 'res'
            // if necessary.
            foreach (Cookie cookie in req) {
              cookie.Expired = true;
              res.Add (cookie);
            }

            return true; // If valid.
//.........这里部分代码省略.........
开发者ID:rynnwang,项目名称:websocket-sharp,代码行数:101,代码来源:Program.cs

示例7: SocketServer

        public SocketServer()
        {
            var wssv = new HttpServer(8140);

            GameEngine gameEngine = new GameEngine();
            ChatEngine chatEngine = new ChatEngine();

            wssv.AddWebSocketService<GameService>("/game", () => new GameService(gameEngine));
            wssv.AddWebSocketService<ChatService>("/chat", () => new ChatService(chatEngine));

            wssv.Start();
            Console.ReadKey(true);
            wssv.Stop();
        }
开发者ID:perara,项目名称:Souls,代码行数:14,代码来源:SocketServer.cs.REMOTE.17348.cs

示例8: Start

    public void Start() {
      using(var sr=new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("X13.Plugins.ui.xst"))) {
        Topic.Import(sr, null);
      }
      if(!Topic.root.Exist("/export/_declarer")) {
        var exp=Topic.root.Get("/export");
        Topic.root.Get<long>("/etc/Broker/security/acls/export").value=0x1F000001;
        exp.Get<string>("_declarer").value="ui_root";
      }
      {
        var assembly = Assembly.GetExecutingAssembly();

        var etf=assembly.GetName().Version.ToString(4).GetHashCode().ToString("X8")+"-";
        _resources=new SortedList<string, Tuple<Stream, string>>();
        foreach(var resourceName in assembly.GetManifestResourceNames().Where(z => z.StartsWith("X13.Plugins.www."))) {
          var stream=assembly.GetManifestResourceStream(resourceName);
          string eTag=etf+stream.Length.ToString("X4");
          _resources[resourceName.Substring(16)]=new Tuple<Stream, string>(stream, eTag);
        }
      }

      _verbose=Topic.root.Get<bool>("/etc/HttpServer/_verbose");
      _disAnonym=Topic.root.Get<bool>("/etc/HttpServer/DisableAnonymus");
      var portD=Topic.root.Get<long>("/local/cfg/HttpServer/_port");

      if(portD.value==0) {
        portD.value=Engine.IsLinux?8080:80;
      }

      _sv = new HttpServer((int)portD.value);
      _sv.Log.Output=WsLog;
#if DEBUG
      _sv.Log.Level=WebSocketSharp.LogLevel.Trace;
#endif
      _sv.RootPath=Path.GetFullPath(Path.GetFullPath("../htdocs"));
      if(!Directory.Exists(_sv.RootPath)) {
        Directory.CreateDirectory(_sv.RootPath);
      }
      _sv.OnGet+=OnGet;
      _sv.AddWebSocketService<ApiV03>("/api/v03");
      _sv.Start();
      if(_sv.IsListening) {
        Log.Info("HttpServer started on {0}:{1} ", Environment.MachineName, _sv.Port.ToString());
      } else {
        Log.Error("HttpServer start failed");
      }
    }
开发者ID:giapdangle,项目名称:X13.Host,代码行数:47,代码来源:HttpWsPl.cs

示例9: Main

    public static void Main (string [] args)
    {
      _httpsv = new HttpServer (4649);
      //_httpsv = new HttpServer (4649, true); // For Secure Connection
#if DEBUG
      // Changing the logging level
      _httpsv.Log.Level = LogLevel.Trace;
#endif
      /* For Secure Connection
      var cert = ConfigurationManager.AppSettings ["ServerCertFile"];
      var password = ConfigurationManager.AppSettings ["CertFilePassword"];
      _httpsv.Certificate = new X509Certificate2 (cert, password);
       */

      /* For HTTP Authentication (Basic/Digest)
      _httpsv.AuthenticationSchemes = AuthenticationSchemes.Basic;
      _httpsv.Realm = "WebSocket Test";
      _httpsv.UserCredentialsFinder = identity => {
        var expected = "nobita";
        return identity.Name == expected
               ? new NetworkCredential (expected, "password", "gunfighter")
               : null;
      };
       */

      // Not to remove inactive clients in WebSocket services periodically
      //_httpsv.KeepClean = false;

      // Setting the document root path
      _httpsv.RootPath = ConfigurationManager.AppSettings ["RootPath"];

      // Setting HTTP method events
      _httpsv.OnGet += (sender, e) => onGet (e);

      // Adding WebSocket services
      _httpsv.AddWebSocketService<Echo> ("/Echo");
      _httpsv.AddWebSocketService<Chat> ("/Chat");

      /* With initializing
      _httpsv.AddWebSocketService<Chat> (
        "/Chat",
        () => new Chat ("Anon#") {
          Protocol = "chat",
          // Checking Origin header
          OriginValidator = value => {
            Uri origin;
            return !value.IsNullOrEmpty () &&
                   Uri.TryCreate (value, UriKind.Absolute, out origin) &&
                   origin.Host == "localhost";
          },
          // Checking Cookies
          CookiesValidator = (req, res) => {
            foreach (Cookie cookie in req) {
              cookie.Expired = true;
              res.Add (cookie);
            }

            return true;
          }
        });
       */

      _httpsv.Start ();
      if (_httpsv.IsListening) {
        Console.WriteLine (
          "An HTTP server listening on port: {0}, providing WebSocket services:", _httpsv.Port);

        foreach (var path in _httpsv.WebSocketServices.Paths)
          Console.WriteLine ("- {0}", path);
      }

      Console.WriteLine ("\nPress Enter key to stop the server...");
      Console.ReadLine ();

      _httpsv.Stop ();
    }
开发者ID:Wappworks,项目名称:websocket-sharp,代码行数:76,代码来源:Program.cs

示例10: StartServer


//.........这里部分代码省略.........
                // run the game the browser reconnects but the system
                // isn't fully ready yet.
                PostCmd cmd = null;
                try
                {
                    cmd = deserializer_.Deserialize<PostCmd>(result);
                }
                catch (System.Exception)
                {
                    m_log.Warn("could't deseralize PostCmd:" + result);
                }
                if (cmd == null || cmd.cmd == null)
                {
                    res.ContentType = "application/json";
                    res.StatusCode = (int)HttpStatusCode.BadRequest;
                    res.WriteContent(System.Text.Encoding.UTF8.GetBytes("{\"error\":\"bad command data: " + cmd.cmd + "\"}"));
                }
                else if (cmd.cmd == "happyFunTimesPingForGame")
                {
                    m_webServerUtils.SendJsonBytes(res, m_ping);
                    return;
                }
                else if (cmd.cmd == "happyFunTimesPing")
                {
                    // Yes reaching up this far is shit :(
                    if (!HFTGameManager.GetInstance().HaveGame())
                    {
                        res.StatusCode = (int)HttpStatusCode.NotFound;
                        return;
                    }

                    m_webServerUtils.SendJsonBytes(res, m_ping);
                    return;
                }
                else if (cmd.cmd == "happyFunTimesRedir")
                {
                    string controllerPath = m_gamePath + m_options.controllerFilename;
                    string redirStr = Serializer.Serialize(new Redir(controllerPath));
                    m_redir = System.Text.Encoding.UTF8.GetBytes(redirStr);
                    m_webServerUtils.SendJsonBytes(res, m_redir);
                    return;
                }
                else
                {
                    res.ContentType = "application/json";
                    res.StatusCode = (int)HttpStatusCode.BadRequest;
                    res.WriteContent(System.Text.Encoding.UTF8.GetBytes("{\"error\":\"unknown cmd: " + cmd.cmd + "\"}"));
                }
                // TODO: use router
            };

            // Not to remove the inactive WebSocket sessions periodically.
            //server.KeepClean = false;

            // To resolve to wait for socket in TIME_WAIT state.
            //server.ReuseAddress = true;

            // Add the WebSocket services.
            //    server.AddWebSocketService<Echo> ("/Echo");
            //    server.AddWebSocketService<Chat> ("/Chat");
            server.AddWebSocketService<HFTSocket>("/");

            /* Add the WebSocket service with initializing.
            server.AddWebSocketService<Chat> (
              "/Chat",
              () => new Chat ("Anon#") {
                // To send the Sec-WebSocket-Protocol header that has a subprotocol name.
                Protocol = "chat",
                // To emit a WebSocket.OnMessage event when receives a ping.
                EmitOnPing = true,
                // To ignore the Sec-WebSocket-Extensions header.
                IgnoreExtensions = true,
                // To validate the Origin header.
                OriginValidator = val => {
                  // Check the value of the Origin header, and return true if valid.
                  Uri origin;
                  return !val.IsNullOrEmpty () &&
                         Uri.TryCreate (val, UriKind.Absolute, out origin) &&
                         origin.Host == "localhost";
                },
                // To validate the Cookies.
                CookiesValidator = (req, res) => {
                  // Check the Cookies in 'req', and set the Cookies to send to the client with 'res'
                  // if necessary.
                  foreach (Cookie cookie in req) {
                    cookie.Expired = true;
                    res.Add (cookie);
                  }
                  return true; // If valid.
                }
              });
             */
            server.Start();
            if (server.IsListening)
            {
                m_log.Info(String.Format("Listening on {0} port {1}, and providing WebSocket services:", server.Address, server.Port));
                //foreach (var path in server.WebSocketServices.Paths) Debug.Log(String.Format("- {0}", path));
            }
            return server;
        }
开发者ID:greggman,项目名称:hft-unity-gamepad,代码行数:101,代码来源:HFTWebServer.cs


注:本文中的HttpServer.AddWebSocketService方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。