websocket-sharp/Example3/Program.cs

90 lines
2.4 KiB
C#
Raw Normal View History

2012-09-10 00:36:22 +08:00
using System;
using System.Configuration;
using System.Security.Cryptography.X509Certificates;
2012-09-10 00:36:22 +08:00
using WebSocketSharp;
using WebSocketSharp.Net;
using WebSocketSharp.Server;
namespace Example3
{
public class Program
{
private static HttpServer _httpsv;
2012-09-10 00:36:22 +08:00
public static void Main (string [] args)
2012-09-10 00:36:22 +08:00
{
_httpsv = new HttpServer (4649);
2014-01-04 02:15:21 +08:00
//_httpsv = new HttpServer (4649, true) // Secure;
#if DEBUG
2013-07-15 19:42:55 +08:00
_httpsv.Log.Level = LogLevel.TRACE;
2014-01-04 02:15:21 +08:00
#endif
/* Secure Connection
var cert = ConfigurationManager.AppSettings ["ServerCertFile"];
var password = ConfigurationManager.AppSettings ["CertFilePassword"];
_httpsv.Certificate = new X509Certificate2 (cert, password);
*/
/* HTTP Authentication (Basic/Digest)
_httpsv.AuthenticationSchemes = AuthenticationSchemes.Basic;
_httpsv.Realm = "WebSocket Test";
_httpsv.UserCredentialsFinder = identity => {
2014-01-27 14:39:27 +08:00
var expected = "nobita";
return identity.Name == expected
? new NetworkCredential (expected, "password", "gunfighter")
: null;
};
*/
//_httpsv.KeepClean = false;
2014-01-04 03:09:23 +08:00
_httpsv.RootPath = ConfigurationManager.AppSettings ["RootPath"];
2014-01-04 02:15:21 +08:00
_httpsv.OnGet += (sender, e) => onGet (e);
_httpsv.AddWebSocketService<Echo> ("/Echo");
_httpsv.AddWebSocketService<Chat> ("/Chat");
2014-02-08 16:05:24 +08:00
//_httpsv.AddWebSocketService<Chat> (
// "/Chat",
// () => new Chat ("Anon#") { Protocol = "chat" });
2012-09-10 00:36:22 +08:00
_httpsv.Start ();
if (_httpsv.IsListening) {
Console.WriteLine (
2014-01-04 02:15:21 +08:00
"An HTTP server listening on port: {0} WebSocket service paths:",
_httpsv.Port);
foreach (var path in _httpsv.WebSocketServices.Paths)
Console.WriteLine (" {0}", path);
}
2012-09-10 00:36:22 +08:00
Console.WriteLine ("\nPress Enter key to stop the server...");
Console.ReadLine ();
2012-09-10 00:36:22 +08:00
2014-01-04 02:15:21 +08:00
_httpsv.Stop ();
2012-09-10 00:36:22 +08:00
}
private static byte [] getContent (string path)
2012-09-10 00:36:22 +08:00
{
if (path == "/")
path += "index.html";
return _httpsv.GetFile (path);
2012-09-10 00:36:22 +08:00
}
private static void onGet (HttpRequestEventArgs eventArgs)
2012-09-10 00:36:22 +08:00
{
2014-01-04 02:15:21 +08:00
var req = eventArgs.Request;
var res = eventArgs.Response;
var content = getContent (req.RawUrl);
if (content != null) {
2014-01-04 02:15:21 +08:00
res.WriteContent (content);
2012-09-10 00:36:22 +08:00
return;
}
2014-01-04 02:15:21 +08:00
res.StatusCode = (int) HttpStatusCode.NotFound;
2012-09-10 00:36:22 +08:00
}
}
}