Git Product home page Git Product logo

uhttpsharp's Introduction

µHttpSharp

A very lightweight & simple embedded http server for c#

Master Provider
Build Status Windows CI Provided By JetBrains and CodeBetter
Build status Windows CI Provided By AppVeyor
Build Status Mono CI Provided by travis-ci

Usage

A NuGet Package is available, Install via NuGet Package Manager :

install-package uHttpSharp

A sample for usage :

using (var httpServer = new HttpServer(new HttpRequestProvider()))
{
	// Normal port 80 :
	httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 80)));
    
	// Ssl Support :
	var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer");
	httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate));

	// Request handling : 
	httpServer.Use((context, next) => {
		Console.WriteLine("Got Request!");
		return next();
	});

	// Handler classes : 
	httpServer.Use(new TimingHandler());
	httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler())
									.With("about", new AboutHandler()));
	httpServer.Use(new FileHandler());
	httpServer.Use(new ErrorHandler());
	
	httpServer.Start();
	
	Console.ReadLine();
}

Features

µHttpSharp is a simple http server inspired by koa, and has the following features :

  • RESTful controllers
  • Ssl Support
  • Easy Chain-Of-Responsibility architecture

Performance

µHttpSharp manages to handle 13000 requests a sec (With Keep-Alive support) on core i5 machine, cpu goes to 27%, memory consumption and number of threads is stable.

ab -n 10000 -c 50 -k -s 2 http://localhost:8000/

This is ApacheBench, Version 2.3 <$Revision: 1528965 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests


Server Software:
Server Hostname:        localhost
Server Port:            8000

Document Path:          /
Document Length:        21 bytes

Concurrency Level:      50
Time taken for tests:   0.707 seconds
Complete requests:      9357
Failed requests:        0
Keep-Alive requests:    9363
Total transferred:      1507527 bytes
HTML transferred:       196644 bytes
Requests per second:    13245.36 [#/sec] (mean)
Time per request:       3.775 [ms] (mean)
Time per request:       0.075 [ms] (mean, across all concurrent requests)
Transfer rate:          2083.53 [Kbytes/sec] received

Connection Times (ms)
			  min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       1
Processing:     1    4   0.7      4      13
Waiting:        1    4   0.7      4      13
Total:          1    4   0.7      4      13

Percentage of the requests served within a certain time (ms)
  50%      4
  66%      4
  75%      4
  80%      4
  90%      4
  95%      4
  98%      5
  99%      9
 100%      4 (longest request)

How To Contribute?

  • Use it
  • Open Issues
  • Fork and Push requests

uhttpsharp's People

Contributors

gavazquez avatar hisleiterj avatar joewhite avatar rancohen1 avatar renovate-bot avatar shanielh avatar win32re avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uhttpsharp's Issues

[HELP] SSL garbage date

After generating a certificate, adding certificate to mozilla (cause it is self signed), it started printing garbage data. Why is that ?
What am I doing wrong ?

Is ist possible to have a login?

Hi!

I think this project is the best and simplest http server for c#. But im wondering, if its possible to handle a login, because i have to have that function in my project.

Greets Marcel

Source for SessionHandler is not available in github

The nuget for uhttpsharp 0.1.6.22 includes a class SessionHandler that is not available in github.
I want the latest version of uhttpsharp source code to debug an issue I'm facing where the CookieStorage ctor fails with an Index out of range error due to incorrect assumption of number of entries in the parsed cookie header:

2017-05-20 11:48:20,298 WARN (HttpClientHandler-22)((null)) Error while serving : 127.0.0.1:53639
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at uhttpsharp.CookiesStorage..ctor(String cookie) in c:\Users\shani\Documents\GitHub\uHttpSharp\uhttpsharp\IHttpContext.cs:line 66
at uhttpsharp.HttpContext..ctor(IHttpRequest request, EndPoint remoteEndPoint) in c:\Users\shani\Documents\GitHub\uHttpSharp\uhttpsharp\HttpContext.cs:line 17
at uhttpsharp.HttpClientHandler.d__1.MoveNext() in c:\Users\shani\Documents\GitHub\uHttpSharp\uhttpsharp\HttpClient.cs:line 82

Thanks!

Remove dependencies?

It would be nice if this project had no external dependencies. Looking at the code, it seems like log4net could be easily replaced by a delegate (passed as optional parameter to HttpServer constructor).

sockets end in close_wait state after some time

Looks like we are missing a time-out on stream reader in uhttpsharp\HttpClient.cs

When remote http client gets disconnected due to some network issues (or because of proxies in between not handling the keep-alive header properly), uHttpSharp library code fails to close the socket, this results in open sockets stuck in close_wait state.
Am new to C# not sure how to add this time out.

 {
        try
        {
            await InitializeStream();

            while (_client.Connected)
            {
                // TODO : Configuration.
                var limitedStream = new NotFlushingStream(new LimitedStream(_stream));

                var request = await _requestProvider.Provide(new MyStreamReader(limitedStream)).ConfigureAwait(false);

                if (request != null)
                {
                    UpdateLastOperationTime();

                    var context = new HttpContext(request, _client.RemoteEndPoint);

                    Logger.InfoFormat("{1} : Got request {0}", request.Uri, _client.RemoteEndPoint);


                    await _requestHandler(context).ConfigureAwait(false);

                    if (context.Response != null)
                    {
                        var streamWriter = new StreamWriter(limitedStream) { AutoFlush = false };
                        streamWriter.NewLine = "\r\n";
                        await WriteResponse(context, streamWriter).ConfigureAwait(false);

                         //v----- connections seem to be stuck here, resulting in piling up of  sockets in close_wait state
                        await limitedStream.ExplicitFlushAsync().ConfigureAwait(false); 

                        if (!request.Headers.KeepAliveConnection() || context.Response.CloseConnection)
                        {
                            _client.Close();
                        }
                    }

                    UpdateLastOperationTime();
                }
                else
                {
                    _client.Close();
                }
            }
        }
        catch (Exception e)
        {
            // Hate people who make bad calls.
            Logger.WarnException(string.Format("Error while serving : {0}", _remoteEndPoint), e);
            _client.Close();
        }

        Logger.InfoFormat("Lost Client {0}", _remoteEndPoint);
    }

Host static project in response

How can I host a static project to the HttpResponse?
I have a simple static index.html file with external CSS and js. I want to start an http-server and host this project on it.

How to add handler for new HTTP method?

Could you please show code snippet, how to add new HTTP method provider/handler (in my case - DLNA - new method called SUBSCRIBE).

And another issue: could you tell me, how to add custom headers to response?

Unable to run demo with HTTPS enabled.

Please add instructions for how to use HTTPS support. Dropping a DER encoded CER file into the dir and un-commenting the line of code produces an "The credentials supplied to the package were not recognized" Exception on the first HTTPS request.

How do I disable logging?

I would like to disable the automatic uhttpsharp log in my console application by either some boolean flag or by changing the logger level. Any help?

Example doesn't work

This needs more examples but also, the provided example doesn't work.

There is no provided TimingHandler IndexHandler AboutHandler ErrorHandler.

The example needs to include some implementation of these, or exclude them.

Support for Post Data

Hi,

Not an issue, more of a request:

Are there any plans to add support to get access to the data from a http POST?

Cheers,

Two repo,Refused

hallo
I was confused with two repo.
And Then I Compare With two.
image

I think it is necessary to explain the difference between the two repo.
Give a reference to each other...And Bug
Thanks for your job.

examples?

how to start the server with HTTPS support by loading server.key (passphrase protected) and server.crt?

how to setup routes URLS?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.