diff --git a/Example3/AssemblyInfo.cs b/Example3/AssemblyInfo.cs index a5e85b3d..b9a88a25 100644 --- a/Example3/AssemblyInfo.cs +++ b/Example3/AssemblyInfo.cs @@ -24,4 +24,3 @@ using System.Runtime.CompilerServices; //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] - diff --git a/Example3/Chat.cs b/Example3/Chat.cs index 73bcbe18..7708a1a7 100644 --- a/Example3/Chat.cs +++ b/Example3/Chat.cs @@ -7,10 +7,9 @@ namespace Example3 { public class Chat : WebSocketBehavior { - private static int _num = 0; - - private string _name; - private string _prefix; + private string _name; + private static int _number = 0; + private string _prefix; public Chat () : this (null) @@ -24,13 +23,15 @@ namespace Example3 private string getName () { - var name = Context.QueryString ["name"]; - return !name.IsNullOrEmpty () ? name : (_prefix + getNum ()); + var name = Context.QueryString["name"]; + return !name.IsNullOrEmpty () + ? name + : (_prefix + getNumber ()); } - private static int getNum () + private static int getNumber () { - return Interlocked.Increment (ref _num); + return Interlocked.Increment (ref _number); } protected override void OnOpen () diff --git a/Example3/Echo.cs b/Example3/Echo.cs index 6d334a68..1e070191 100644 --- a/Example3/Echo.cs +++ b/Example3/Echo.cs @@ -8,11 +8,8 @@ namespace Example3 { protected override void OnMessage (MessageEventArgs e) { - var name = Context.QueryString ["name"]; - var msg = !name.IsNullOrEmpty () - ? String.Format ("'{0}' to {1}", e.Data, name) - : e.Data; - + var name = Context.QueryString["name"]; + var msg = !name.IsNullOrEmpty () ? String.Format ("'{0}' to {1}", e.Data, name) : e.Data; Send (msg); } } diff --git a/Example3/Program.cs b/Example3/Program.cs index eb22301d..f6c3cfc9 100644 --- a/Example3/Program.cs +++ b/Example3/Program.cs @@ -1,6 +1,7 @@ using System; using System.Configuration; using System.Security.Cryptography.X509Certificates; +using System.Text; using WebSocketSharp; using WebSocketSharp.Net; using WebSocketSharp.Server; @@ -9,26 +10,32 @@ namespace Example3 { public class Program { - private static HttpServer _httpsv; - - public static void Main (string [] args) + public static void Main (string[] args) { - _httpsv = new HttpServer (4649); - //_httpsv = new HttpServer (4649, true); // For Secure Connection + /* 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. + */ + var httpsv = new HttpServer (4649); + //httpsv = new HttpServer (4649, true); #if DEBUG - // Changing the logging level - _httpsv.Log.Level = LogLevel.Trace; + // 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 - /* For Secure Connection - var cert = ConfigurationManager.AppSettings ["ServerCertFile"]; - var password = ConfigurationManager.AppSettings ["CertFilePassword"]; - _httpsv.Certificate = new X509Certificate2 (cert, password); + /* To provide the 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 => { + /* To provide the 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") @@ -36,32 +43,52 @@ namespace Example3 }; */ - // Not to remove inactive clients in WebSocket services periodically - //_httpsv.KeepClean = false; + // To set the document root path. + httpsv.RootPath = ConfigurationManager.AppSettings["RootPath"]; - // Setting 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; - // Setting HTTP method events - _httpsv.OnGet += (sender, e) => onGet (e); + var path = req.RawUrl; + if (path == "/") + path += "index.html"; - // Adding WebSocket services - _httpsv.AddWebSocketService ("/Echo"); - _httpsv.AddWebSocketService ("/Chat"); + var content = httpsv.GetFile (path); + if (content == null) { + res.StatusCode = (int) HttpStatusCode.NotFound; + return; + } - /* With initializing - _httpsv.AddWebSocketService ( + 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; + + // Add the WebSocket services. + httpsv.AddWebSocketService ("/Echo"); + httpsv.AddWebSocketService ("/Chat"); + + /* Add the WebSocket service with initializing. + httpsv.AddWebSocketService ( "/Chat", () => new Chat ("Anon#") { Protocol = "chat", - // Checking Origin header + // To validate the Origin header. OriginValidator = value => { Uri origin; return !value.IsNullOrEmpty () && Uri.TryCreate (value, UriKind.Absolute, out origin) && origin.Host == "localhost"; }, - // Checking Cookies + // To validate the Cookies. CookiesValidator = (req, res) => { foreach (Cookie cookie in req) { cookie.Expired = true; @@ -73,40 +100,17 @@ namespace Example3 }); */ - _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) + httpsv.Start (); + if (httpsv.IsListening) { + Console.WriteLine ("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 (); - } - - private static byte [] getContent (string path) - { - if (path == "/") - path += "index.html"; - - return _httpsv.GetFile (path); - } - - private static void onGet (HttpRequestEventArgs e) - { - var req = e.Request; - var res = e.Response; - var content = getContent (req.RawUrl); - if (content != null) { - res.WriteContent (content); - return; - } - - res.StatusCode = (int) HttpStatusCode.NotFound; + httpsv.Stop (); } } } diff --git a/Example3/Public/Js/echotest.js b/Example3/Public/Js/echotest.js index 5157ded5..b6054455 100644 --- a/Example3/Public/Js/echotest.js +++ b/Example3/Public/Js/echotest.js @@ -1,68 +1,68 @@ -/** +/* * echotest.js - * Derived from Echo Test of WebSocket.org (http://www.websocket.org/echo.html) + * + * Derived from Echo Test of WebSocket.org (http://www.websocket.org/echo.html). * * Copyright (c) 2012 Kaazing Corporation. - * */ -var wsUri = "ws://localhost:4649/Echo"; -//var wsUri = "wss://localhost:4649/Echo"; +var url = "ws://localhost:4649/Echo"; +//var url = "wss://localhost:4649/Echo"; var output; -function init(){ - output = document.getElementById("output"); - testWebSocket(); +function init () { + output = document.getElementById ("output"); + doWebSocket (); } -function testWebSocket(){ - websocket = new WebSocket(wsUri); +function doWebSocket () { + websocket = new WebSocket (url); - websocket.onopen = function(evt){ - onOpen(evt) + websocket.onopen = function (evt) { + onOpen (evt) }; - websocket.onclose = function(evt){ - onClose(evt) + websocket.onclose = function (evt) { + onClose (evt) }; - websocket.onmessage = function(evt){ - onMessage(evt) + websocket.onmessage = function (evt) { + onMessage (evt) }; - websocket.onerror = function(evt){ - onError(evt) + websocket.onerror = function (evt) { + onError (evt) }; } -function onOpen(evt){ - writeToScreen("CONNECTED"); - doSend("WebSocket rocks"); +function onOpen (evt) { + writeToScreen ("CONNECTED"); + send ("WebSocket rocks"); } -function onClose(evt){ - writeToScreen("DISCONNECTED"); +function onClose (evt) { + writeToScreen ("DISCONNECTED"); } -function onMessage(evt){ - writeToScreen('RESPONSE: ' + evt.data + ''); - websocket.close(); +function onMessage (evt) { + writeToScreen ('RESPONSE: ' + evt.data + ''); + websocket.close (); } -function onError(evt){ +function onError (evt) { writeToScreen('ERROR: ' + evt.data + ''); } -function doSend(message){ - writeToScreen("SENT: " + message); - websocket.send(message); +function send (message) { + writeToScreen ("SENT: " + message); + websocket.send (message); } -function writeToScreen(message){ - var pre = document.createElement("p"); +function writeToScreen (message) { + var pre = document.createElement ("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; - output.appendChild(pre); + output.appendChild (pre); } -window.addEventListener("load", init, false); \ No newline at end of file +window.addEventListener ("load", init, false); \ No newline at end of file