Skip to content

Commit

Permalink
Checking HttpConnection
Browse files Browse the repository at this point in the history
  • Loading branch information
geoperez committed Feb 20, 2017
1 parent 919e05d commit 1bc76ac
Show file tree
Hide file tree
Showing 15 changed files with 99 additions and 175 deletions.
14 changes: 2 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,6 @@ namespace Company.Project
//server.Module<Modules.StaticFilesWebModule>().DefaultDocument = "index.html";
// Once we've registered our modules and configured them, we call the RunAsync() method.
// This is a non-blocking method (it return immediately) so in this case we avoid
// disposing of the object until a key is pressed.
//server.Run();
server.RunAsync();

// Fire up the browser to show the content if we are debugging!
Expand Down Expand Up @@ -150,22 +147,15 @@ namespace Company.Project
.WithLocalSession()
.WithStaticFolderAt("c:/web");

var cts = new CancellationTokenSource();
var cts = new CancellationTokenSource();
var task = server.RunAsync(cts.Token);

// Fire up the browser to show the content if we are debugging!
#if DEBUG
var browser = new System.Diagnostics.Process()
{
StartInfo = new System.Diagnostics.ProcessStartInfo(url) {UseShellExecute = true}
};
browser.Start();
#endif
// Wait for any key to be pressed before disposing of our web server.
// In a service we'd manage the lifecycle of of our web server using
// something like a BackgroundWorker or a ManualResetEvent.
Console.ReadKey(true);
cts.Cancel();

try
{
task.Wait();
Expand Down
20 changes: 10 additions & 10 deletions src/Unosquare.Labs.EmbedIO.Samples/PeopleController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Unosquare.Labs.EmbedIO.Modules;
using Modules;
using System.Threading.Tasks;
using Tubular;
using Swan;
using Unosquare.Tubular.ObjectModel;
using Tubular.ObjectModel;
#if NET46
using System.Net;
#else
Expand Down Expand Up @@ -54,14 +54,14 @@ public bool GetPeople(WebServer server, HttpListenerContext context)
return context.JsonResponse(_dbContext.People.SelectAll().First());

// otherwise, we need to parse the key and respond with the entity accordingly
int key = 0;
if (int.TryParse(lastSegment, out key))
{
var single = _dbContext.People.Single(key);
int key;
if (!int.TryParse(lastSegment, out key))
throw new KeyNotFoundException("Key Not Found: " + lastSegment);

if (single != null)
return context.JsonResponse(single);
}
var single = _dbContext.People.Single(key);

if (single != null)
return context.JsonResponse(single);

throw new KeyNotFoundException("Key Not Found: " + lastSegment);
}
Expand All @@ -86,7 +86,7 @@ public bool GetPeople(WebServer server, HttpListenerContext context)
/// <param name="server">The server.</param>
/// <param name="context">The context.</param>
/// <returns></returns>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">Key Not Found: + lastSegment</exception>
/// <exception cref="KeyNotFoundException">Key Not Found: + lastSegment</exception>
[WebApiHandler(HttpVerbs.Post, RelativePath + "people/*")]
public async Task<bool> PostPeople(WebServer server, HttpListenerContext context)
{
Expand Down
20 changes: 8 additions & 12 deletions src/Unosquare.Labs.EmbedIO.Samples/Program.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
namespace Unosquare.Labs.EmbedIO.Samples
{
using Swan;
using Modules;
using System;

internal class Program
{
public static readonly bool IsMono = Type.GetType("Mono.Runtime") != null;

/// <summary>
/// Defines the entry point of the application.
/// </summary>
/// <param name="args">The arguments.</param>
private static void Main(string[] args)
{
Console.WriteLine("Running on Mono Runtime: {0}", IsMono);
$"Running on Mono Runtime: {Runtime.IsUsingMonoRuntime}".Info();

var url = "http://localhost:9696/";
var url = "http://localhost:8787/";

if (args.Length > 0)
url = args[0];
Expand Down Expand Up @@ -56,10 +55,10 @@ private static void Main(string[] args)
// If we want to enable sessions, we simply register the LocalSessionModule
// Beware that this is an in-memory session storage mechanism so, avoid storing very large objects.
// You can use the server.GetSession() method to get the SessionInfo object and manupulate it.
server.RegisterModule(new Modules.LocalSessionModule());
server.RegisterModule(new LocalSessionModule());

// Set the CORS Rules
server.RegisterModule(new Modules.CorsModule(
server.RegisterModule(new CorsModule(
// Origins, separated by comma without last slash
"http://client.cors-api.appspot.com,http://unosquare.github.io,http://run.plnkr.co",
// Allowed headers
Expand All @@ -69,7 +68,7 @@ private static void Main(string[] args)

// Register the static files server. See the html folder of this project. Also notice that
// the files under the html folder have Copy To Output Folder = Copy if Newer
StaticFilesSample.Setup(server, !IsMono);
StaticFilesSample.Setup(server, useGzip: Runtime.IsUsingMonoRuntime == false);

// Register the Web Api Module. See the Setup method to find out how to do it
// It registers the WebApiModule and registers the controller(s) -- that's all.
Expand All @@ -81,14 +80,11 @@ private static void Main(string[] args)

server.RegisterModule(new FallbackModule((ws, ctx) =>
{
ctx.JsonResponse(new { Message = "Error " });
ctx.JsonResponse(new {Message = "Error "});
return true;
}));

// Once we've registered our modules and configured them, we call the Run() method.
// This is a non-blocking method (it return immediately) so in this case we avoid
// disposing of the object until a key is pressed.
//server.Run();
// Once we've registered our modules and configured them, we call the RunAsync() method.
server.RunAsync();

// Fire up the browser to show the content!
Expand Down
10 changes: 10 additions & 0 deletions src/Unosquare.Labs.EmbedIO.Samples/WebSocketsSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Text;
using Modules;
using Swan;
#if NET46
using System.Threading;
using System.Net.WebSockets;
Expand Down Expand Up @@ -47,6 +48,12 @@ protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuf
{
foreach (var ws in WebSockets)
{
#if !NET46
if (ws.UserEndPoint == null)
"Error ws.UserEndPoint".Warn();

$"WebSocket info: {ws.UserEndPoint}".Info();
#endif
if (ws != context)
Send(ws, Encoding.UTF8.GetString(rxBuffer));
}
Expand Down Expand Up @@ -92,6 +99,9 @@ protected override void OnFrameReceived(WebSocketContext context, byte[] rxBuffe
protected override void OnClientDisconnected(WebSocketContext context)
{
Broadcast("Someone left the chat room.");
#if !NET46
$"WebSocket closed: {context.UserEndPoint}".Info();
#endif
}
}

Expand Down
32 changes: 13 additions & 19 deletions src/Unosquare.Labs.EmbedIO.Samples/html/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,13 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">

<title ng-controller="TitleController as title">EmbedIO - {{title.content}} - Unosquare Labs</title>

<link rel="stylesheet" href="//cdn.jsdelivr.net/fontawesome/latest/css/font-awesome.min.css">
<link rel="stylesheet" href="//npmcdn.com/angular-toastr/dist/angular-toastr.css" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/scripts/tubular/tubular-bundle.css">
<link rel="stylesheet" href="/css/theme.css">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

<script src="//cdn.jsdelivr.net/g/[email protected](angular.min.js+angular-animate.min.js+angular-route.min.js),[email protected](ui-bootstrap.min.js+ui-bootstrap-tpls.min.js),tubular,blob.js(Blob.js),[email protected]"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-local-storage/0.1.5/angular-local-storage.min.js"></script>
<script src="//npmcdn.com/angular-toastr/dist/angular-toastr.tpls.js"></script>
<script src="//cdn.jsdelivr.net/tubular/1.0.1/tubular-bundle.min.js"></script>

<script src="/scripts/app.services.js"></script>
<script src="/scripts/app.routes.js"></script>
<script src="/scripts/app.controllers.js"></script>
<script src="/scripts/app.directives.js"></script>
<script src="/scripts/app.js"></script>
</head>

<body>
Expand All @@ -37,8 +19,20 @@
<hr />
<footer>
<div class="alert alert-info" role="alert">Location: {{menu.whereAmI() | json}}</div>
© <script type="text/javascript">document.write(new Date().getFullYear());</script> unosquare
©
<script type="text/javascript">document.write(new Date().getFullYear());</script> unosquare
</footer>
</div>

<script src="//cdn.jsdelivr.net/g/[email protected](angular.min.js+angular-animate.min.js+angular-route.min.js),[email protected](ui-bootstrap.min.js+ui-bootstrap-tpls.min.js),momentjs,tubular,[email protected]"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-local-storage/0.1.5/angular-local-storage.min.js"></script>
<script src="//npmcdn.com/angular-toastr/dist/angular-toastr.tpls.js"></script>
<script src="//cdn.jsdelivr.net/tubular/1.0.1/tubular-bundle.min.js"></script>

<script src="/scripts/app.services.js"></script>
<script src="/scripts/app.routes.js"></script>
<script src="/scripts/app.controllers.js"></script>
<script src="/scripts/app.directives.js"></script>
<script src="/scripts/app.js"></script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
.controller('TitleController', ['$scope', '$route', function ($scope, $route) {
var me = this;
me.content = "Home";
$scope.$on('$routeChangeSuccess', function (currentRoute, previousRoute) {
$scope.$on('$routeChangeSuccess', function () {
me.content = $route.current.title;
});
}])
Expand All @@ -25,7 +25,7 @@
var me = this;
me.nickName = "Bob";
me.message = "";
me.wsUri = "ws://localhost:9696/chat";
me.wsUri = "ws://" + document.location.hostname + ":" + document.location.port + "/chat";
me.messages = [];

me.websocket = new WebSocket(me.wsUri);
Expand Down Expand Up @@ -91,7 +91,7 @@
.controller('CmdController', ['$scope', function ($scope) {
var me = this;
me.command = "";
me.wsUri = "ws://localhost:9696/terminal";
me.wsUri = "ws://" + document.location.hostname + ":" + document.location.port + "/terminal";
me.commands = "";

me.scrollBottom = function () {
Expand Down
2 changes: 1 addition & 1 deletion src/Unosquare.Labs.EmbedIO.Samples/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"Microsoft.Data.SQLite": "1.1.0",
"Unosquare.Labs.EmbedIO": { "target": "project" },
"Tubular.ServerSide": "1.1.3",
"LiteLib": "0.9.10"
"LiteLib": "0.11.0"
},

"frameworks": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ private void OnRead(IAsyncResult baseAres)
}
catch (Exception e)
{
_context.Connection.SendError(e.Message, 400);
ares.Complete(e);
}
}
Expand Down
5 changes: 2 additions & 3 deletions src/Unosquare.Labs.EmbedIO/System.Net/EndPointListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
#if SSL
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
#endif

Expand Down Expand Up @@ -112,15 +112,14 @@ private static void Accept(Socket socket, SocketAsyncEventArgs e, ref Socket acc
}
}


private static void ProcessAccept(SocketAsyncEventArgs args)
{
Socket accepted = null;
if (args.SocketError == SocketError.Success)
accepted = args.AcceptSocket;

var epl = (EndPointListener) args.UserToken;

Accept(epl._sock, args, ref accepted);
if (accepted == null)
return;
Expand Down
25 changes: 12 additions & 13 deletions src/Unosquare.Labs.EmbedIO/System.Net/EndPointManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,14 @@ namespace Unosquare.Net
{
internal static class EndPointManager
{
// Dictionary<IPAddress, Dictionary<int, EndPointListener>>
static readonly Hashtable _ipToEndpoints = new Hashtable();
private static readonly Hashtable IPToEndpoints = new Hashtable();

public static void AddListener(HttpListener listener)
{
var added = new ArrayList();
try
{
lock (_ipToEndpoints)
lock (IPToEndpoints)
{
foreach (var prefix in listener.Prefixes)
{
Expand All @@ -64,13 +63,13 @@ public static void AddListener(HttpListener listener)

public static void AddPrefix(string prefix, HttpListener listener)
{
lock (_ipToEndpoints)
lock (IPToEndpoints)
{
AddPrefixInternal(prefix, listener);
}
}

static void AddPrefixInternal(string p, HttpListener listener)
private static void AddPrefixInternal(string p, HttpListener listener)
{
var lp = new ListenerPrefix(p);
if (lp.Path.IndexOf('%') != -1)
Expand Down Expand Up @@ -107,14 +106,14 @@ private static EndPointListener GetEpListener(string host, int port, HttpListene
}
}
Hashtable p = null; // Dictionary<int, EndPointListener>
if (_ipToEndpoints.ContainsKey(addr))
if (IPToEndpoints.ContainsKey(addr))
{
p = (Hashtable)_ipToEndpoints[addr];
p = (Hashtable)IPToEndpoints[addr];
}
else
{
p = new Hashtable();
_ipToEndpoints[addr] = p;
IPToEndpoints[addr] = p;
}

EndPointListener epl;
Expand All @@ -133,22 +132,22 @@ private static EndPointListener GetEpListener(string host, int port, HttpListene

public static void RemoveEndPoint(EndPointListener epl, IPEndPoint ep)
{
lock (_ipToEndpoints)
lock (IPToEndpoints)
{
// Dictionary<int, EndPointListener> p
var p = (Hashtable)_ipToEndpoints[ep.Address];
var p = (Hashtable)IPToEndpoints[ep.Address];
p.Remove(ep.Port);
if (p.Count == 0)
{
_ipToEndpoints.Remove(ep.Address);
IPToEndpoints.Remove(ep.Address);
}
epl.Close();
}
}

public static void RemoveListener(HttpListener listener)
{
lock (_ipToEndpoints)
lock (IPToEndpoints)
{
foreach (var prefix in listener.Prefixes)
{
Expand All @@ -159,7 +158,7 @@ public static void RemoveListener(HttpListener listener)

public static void RemovePrefix(string prefix, HttpListener listener)
{
lock (_ipToEndpoints)
lock (IPToEndpoints)
{
RemovePrefixInternal(prefix, listener);
}
Expand Down
Loading

0 comments on commit 1bc76ac

Please sign in to comment.