Program.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. using System;
  2. using System.Configuration;
  3. using System.Security.Cryptography.X509Certificates;
  4. using System.Text;
  5. using WebSocketSharp;
  6. using WebSocketSharp.Net;
  7. using WebSocketSharp.Server;
  8. namespace Example3
  9. {
  10. public class Program
  11. {
  12. public static void Main (string[] args)
  13. {
  14. // Create a new instance of the HttpServer class.
  15. //
  16. // If you would like to provide the secure connection, you should
  17. // create a new instance with the 'secure' parameter set to true or
  18. // with an https scheme HTTP URL.
  19. var httpsv = new HttpServer (4649);
  20. //var httpsv = new HttpServer (5963, true);
  21. //var httpsv = new HttpServer (System.Net.IPAddress.Any, 4649);
  22. //var httpsv = new HttpServer (System.Net.IPAddress.Any, 5963, true);
  23. //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Any, 4649);
  24. //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Any, 5963, true);
  25. //var httpsv = new HttpServer ("http://0.0.0.0:4649");
  26. //var httpsv = new HttpServer ("https://0.0.0.0:5963");
  27. //var httpsv = new HttpServer ("http://[::0]:4649");
  28. //var httpsv = new HttpServer ("https://[::0]:5963");
  29. //var httpsv = new HttpServer (System.Net.IPAddress.Loopback, 4649);
  30. //var httpsv = new HttpServer (System.Net.IPAddress.Loopback, 5963, true);
  31. //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Loopback, 4649);
  32. //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Loopback, 5963, true);
  33. //var httpsv = new HttpServer ("http://localhost:4649");
  34. //var httpsv = new HttpServer ("https://localhost:5963");
  35. //var httpsv = new HttpServer ("http://127.0.0.1:4649");
  36. //var httpsv = new HttpServer ("https://127.0.0.1:5963");
  37. //var httpsv = new HttpServer ("http://[::1]:4649");
  38. //var httpsv = new HttpServer ("https://[::1]:5963");
  39. #if DEBUG
  40. // To change the logging level.
  41. httpsv.Log.Level = LogLevel.Trace;
  42. // To change the wait time for the response to the WebSocket Ping or Close.
  43. //httpsv.WaitTime = TimeSpan.FromSeconds (2);
  44. // Not to remove the inactive WebSocket sessions periodically.
  45. //httpsv.KeepClean = false;
  46. #endif
  47. // To provide the secure connection.
  48. /*
  49. var cert = ConfigurationManager.AppSettings["ServerCertFile"];
  50. var passwd = ConfigurationManager.AppSettings["CertFilePassword"];
  51. httpsv.SslConfiguration.ServerCertificate = new X509Certificate2 (cert, passwd);
  52. */
  53. // To provide the HTTP Authentication (Basic/Digest).
  54. /*
  55. httpsv.AuthenticationSchemes = AuthenticationSchemes.Basic;
  56. httpsv.Realm = "WebSocket Test";
  57. httpsv.UserCredentialsFinder = id => {
  58. var name = id.Name;
  59. // Return user name, password, and roles.
  60. return name == "nobita"
  61. ? new NetworkCredential (name, "password", "gunfighter")
  62. : null; // If the user credentials are not found.
  63. };
  64. */
  65. // To resolve to wait for socket in TIME_WAIT state.
  66. //httpsv.ReuseAddress = true;
  67. // Set the document root path.
  68. httpsv.DocumentRootPath = ConfigurationManager.AppSettings["DocumentRootPath"];
  69. // Set the HTTP GET request event.
  70. httpsv.OnGet += (sender, e) => {
  71. var req = e.Request;
  72. var res = e.Response;
  73. var path = req.RawUrl;
  74. if (path == "/")
  75. path += "index.html";
  76. byte[] contents;
  77. if (!e.TryReadFile (path, out contents)) {
  78. res.StatusCode = (int) HttpStatusCode.NotFound;
  79. return;
  80. }
  81. if (path.EndsWith (".html")) {
  82. res.ContentType = "text/html";
  83. res.ContentEncoding = Encoding.UTF8;
  84. }
  85. else if (path.EndsWith (".js")) {
  86. res.ContentType = "application/javascript";
  87. res.ContentEncoding = Encoding.UTF8;
  88. }
  89. res.ContentLength64 = contents.LongLength;
  90. res.Close (contents, true);
  91. };
  92. // Add the WebSocket services.
  93. httpsv.AddWebSocketService<Echo> ("/Echo");
  94. httpsv.AddWebSocketService<Chat> ("/Chat");
  95. // Add the WebSocket service with initializing.
  96. /*
  97. httpsv.AddWebSocketService<Chat> (
  98. "/Chat",
  99. s => {
  100. s.Prefix = "Anon#";
  101. // To send the Sec-WebSocket-Protocol header that has a subprotocol name.
  102. s.Protocol = "chat";
  103. // To ignore the Sec-WebSocket-Extensions header.
  104. s.IgnoreExtensions = true;
  105. // To emit a WebSocket.OnMessage event when receives a ping.
  106. s.EmitOnPing = true;
  107. // To validate the Origin header.
  108. s.OriginValidator = val => {
  109. // Check the value of the Origin header, and return true if valid.
  110. Uri origin;
  111. return !val.IsNullOrEmpty ()
  112. && Uri.TryCreate (val, UriKind.Absolute, out origin)
  113. && origin.Host == "localhost";
  114. };
  115. // To validate the cookies.
  116. s.CookiesValidator = (req, res) => {
  117. // Check the cookies in 'req', and set the cookies to send to
  118. // the client with 'res' if necessary.
  119. foreach (var cookie in req) {
  120. cookie.Expired = true;
  121. res.Add (cookie);
  122. }
  123. return true; // If valid.
  124. };
  125. }
  126. );
  127. */
  128. httpsv.Start ();
  129. if (httpsv.IsListening) {
  130. Console.WriteLine ("Listening on port {0}, and providing WebSocket services:", httpsv.Port);
  131. foreach (var path in httpsv.WebSocketServices.Paths)
  132. Console.WriteLine ("- {0}", path);
  133. }
  134. Console.WriteLine ("\nPress Enter key to stop the server...");
  135. Console.ReadLine ();
  136. httpsv.Stop ();
  137. }
  138. }
  139. }