You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.5 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. using System;
  2. using System.Configuration;
  3. using System.Security.Cryptography.X509Certificates;
  4. using WebSocketSharp;
  5. using WebSocketSharp.Net;
  6. using WebSocketSharp.Server;
  7. namespace Example2
  8. {
  9. public class Program
  10. {
  11. public static void Main (string [] args)
  12. {
  13. var wssv = new WebSocketServer (4649);
  14. //var wssv = new WebSocketServer (4649, true); // For Secure Connection
  15. //var wssv = new WebSocketServer ("ws://localhost:4649");
  16. //var wssv = new WebSocketServer ("wss://localhost:4649"); // For Secure Connection
  17. #if DEBUG
  18. // Changing the logging level
  19. wssv.Log.Level = LogLevel.Trace;
  20. #endif
  21. /* For Secure Connection
  22. var cert = ConfigurationManager.AppSettings ["ServerCertFile"];
  23. var password = ConfigurationManager.AppSettings ["CertFilePassword"];
  24. wssv.Certificate = new X509Certificate2 (cert, password);
  25. */
  26. /* For HTTP Authentication (Basic/Digest)
  27. wssv.AuthenticationSchemes = AuthenticationSchemes.Basic;
  28. wssv.Realm = "WebSocket Test";
  29. wssv.UserCredentialsFinder = identity => {
  30. var expected = "nobita";
  31. return identity.Name == expected
  32. ? new NetworkCredential (expected, "password", "gunfighter")
  33. : null;
  34. };
  35. */
  36. // Not to remove inactive clients periodically
  37. //wssv.KeepClean = false;
  38. // Adding WebSocket services
  39. wssv.AddWebSocketService<Echo> ("/Echo");
  40. wssv.AddWebSocketService<Chat> ("/Chat");
  41. /* With initializing
  42. wssv.AddWebSocketService<Chat> (
  43. "/Chat",
  44. () => new Chat ("Anon#") {
  45. Protocol = "chat",
  46. // Checking Origin header
  47. OriginValidator = value => {
  48. Uri origin;
  49. return !value.IsNullOrEmpty () &&
  50. Uri.TryCreate (value, UriKind.Absolute, out origin) &&
  51. origin.Host == "localhost";
  52. },
  53. // Checking Cookies
  54. CookiesValidator = (req, res) => {
  55. foreach (Cookie cookie in req) {
  56. cookie.Expired = true;
  57. res.Add (cookie);
  58. }
  59. return true;
  60. }
  61. });
  62. */
  63. wssv.Start ();
  64. if (wssv.IsListening) {
  65. Console.WriteLine (
  66. "A WebSocket server listening on port: {0}, providing services:", wssv.Port);
  67. foreach (var path in wssv.WebSocketServices.Paths)
  68. Console.WriteLine ("- {0}", path);
  69. }
  70. Console.WriteLine ("\nPress Enter key to stop the server...");
  71. Console.ReadLine ();
  72. wssv.Stop ();
  73. }
  74. }
  75. }