Rim.Client

Advanced WebSocket Client and Connectors.


Keywords
websocket, client, tcp, connector, http-server, mvc-architecture, websocket-client, websocket-server
License
GPL-3.0
Install
Install-Package Rim.Client -Version 3.2.0-beta

Documentation

Rim

Rim is a .NET Core 2.1 lightweight HTTP Server.
Rim provides advanced WebSocket server management and includes WebSocket clients. So you can handle your web site requests and web socket requests in same http server.
Rim.Server supports HTTP Requests with request handler implementation.
Rim.Mvc supports MVC Design seems like ASP.NET MVC
Rim.Mvc.Auth.Jwt supports JSON Web Token for authentication and authorization


Rim.Server NuGet Package
Rim.Mvc NuGet Package
Rim.Mvc.Auth.Jwt NuGet Package

Rim.Mvc uses Rim.Server as infrastructure. If you want to use Rim.Mvc you can use all features of Rim.Server.
Similarly, Rİm.Mvc.Auth.Jwt is a library of Rim.Mvc.

Rim.Server Features
  • HTTP Requests can be handled with IHttpRequestHandler interface implementation.
  • GZIP Content Encoding
  • SSL Support for HTTPS and WSS protocols
  • Advanced WebSocket Server Management
  • Multiple HTTP Servers in same application
  • Advanced WebSocket Client
  • Connected, Disconnected, Text Receive, Binary Receive events and virtual methods for websockets
  • Sync / Async Http Server
  • Firewall implementation and default IP restrict firewall
  • Maximum request length options
  • Customizable WebSocket ping interval
  • WebSocket Client management with interface implementation (also has default container manager)
  • Error logging with IErrorLogger interface implementation
  • HTTP QueryString, Forms are supported with HTML Encode/Decode
  • Dns Resolver supports all domain kinds
  • Maximum Pending Connection options
  • Custom Client Factory implementation
Rim.Mvc Features
  • Rim.Mvc has it's own Service Container for Dependency Inversion.
  • Nearly 4 times faster than ASP.NET Core
  • Controllers, derived from RimController class with Server, Request, Response, User properties.
  • Actions returns IActionResult, Rim.Mvc includes HtmlResult, JsonResult, XmlResult, StringResult, StatusCodeResult. Also other result types can be created.
  • Attributes for each HTTP Method with routing.
  • For controllers, Route attribute can change controller's route.
  • [controller], [action], {parameter}, {?optionalParameter} route patterns are supported.
  • Authorize attribute can be used on controllers and actions.
  • You can pass Role names (one or multiple), Claim names (one or multiple) or policy name to Authorize attribute. You can manage your authorization with no policy too.
  • For action parameters there are FromBody, FromForm, FromHeader, FromQuery, FromRoute attributes to specify parameter source.
  • There are two kind of filters IControllerFilter and IActionFilter
  • You can manipulate each request with middleware function.
  • Policy container, quick and basic policy creation with static methods of Policy class
Rim.Mvc.Auth.Jwt Features
  • Can handle Authorize attribute of Rim.Mvc
  • With JwtProvider, you can create JWT tokens or refresh or validate manually if you want.
  • In controller or filter context objects, You can reach ClaimsPrincipal of token with User property

Usage

You can use RimServer for many purposes such as WebSocket Client, Http Server, WebSocket Server, and multiple purposes. You can also use WebSockets with Rim.Mvc.

Options

RimServer needs some options to run. You can set the options with ServerOptions class or with options json file. If you choose JSON file implementation, RimServer requires one of these files server.json, rimserver.json, rim.json

Sample RimServer JSON Options file seems like;

{
  "Port": 80,
  "PingInterval": 60000,
  "MaximumRequestLength": 10240,
  "MaximumPendingConnections" : 100,
  "UseSecureConnection": false,
  "CertificateFilename": null,
  "IsDevelopment": false,
  "AllowedHosts": [
      "*"
  ]
}

Port is listening port number
PinInterval is ping interval from server side to client side in milliseconds for WebSocket clients.
MaximumRequestLength is after TCP connection is accepted, maximum data length of first request in bytes.
MaximumPendingConnections is maximum pending connection in queue size. When the limit is exceeded next connection request, the request is rejected instantly.
useSecureConnection is for SSL Servers. If true, you need to specify CertificateFilename option. Server waits SSL requests and SSL handshaking.
CertificateFilename is SSL filename for server. This file must be exported text-based certificate encypted data file (such as pfx)
IsDevelopment is for debugging all errors via IErrorLogger interface. Use only on Debug modes, this logging operation may hurt performance. With Rim.Mvc, development mode shows internal server errors as HTTP Responses.

WebSocket Server

In order to start new WebSocket Server, you should create new ClientFactory class and imğlement from IClientFactory interface. When a new TCP Connection request is accepted, HttpServer reads the request. After WebSocket handshaking, an object must be created belongs the TCP connection. This IClientFactory implementation, does this work. You should implement the interface and in the Create method, the object instance must be created (derived from ServerSocket).

You can check Sample.WebSocket.Server project for basic usage.
Here is a quick guide to create new WebSocket server:

public class Client : ServerSocket
{
    public Client(HttpServer server, HttpRequest request, TcpClient client) : base(server, request, client)
    {
    }

    protected override void OnBinaryReceived(byte[] payload)
    {
    }

    protected override void OnConnected()
    {
        Console.WriteLine("Client Connected");
    }

    protected override void OnDisconnected()
    {
        Console.WriteLine("Client Disconnected");
    }

    protected override void OnMessageReceived(string message)
    {
        Console.WriteLine("# " + message);
    }
}

public class ClientFactory : IClientFactory
{
    public ServerSocket Create(HttpServer server, HttpRequest request, TcpClient client)
    {
        return new Client(server, request, client);
    }
}

class Program
{
    static void Main(string[] args)
    {
        IClientFactory factory = new ClientFactory();
        HttpServer server = HttpServer.CreateWebSocket(factory);
        server.Start(false);
    }
}

WebSocket Client

ClientSocket is a client-side WebSocket object of Rim.Server.
There are Connect, Disconnect, MessageReceived, BinaryReceived events for all WebSocket events.
You can also create a new class and derive from ClientSocket and override virtual methods.

ClientSocket client = new ClientSocket();

client.Connected += (sender) => Console.WriteLine("Connected");
client.Disconnected += (sender) => Console.WriteLine("Disconnected");
client.MessageReceived += (sender, message) => Console.WriteLine("# " + message);

client.Connect("ws://127.0.0.1/connect");

while(true)
{
    string line = Console.ReadLine();
    client.Send(line);
}

HTTP Server

RimServer is simple and fast HTTP Server. It can be 5 times after than ASP.NET Core Web Application. For basic HTTP Server requirements, or when you need more performance, you can use RimServer for only HTTP Server operations.

In order to handle HTTP Requests, you need to create new class and implement IHttpRequestHandler interface. When user sends an HTTP request, RimServer calls Request method of IHttpRequestHandler implemented class. You can use response parameter to create new response.

Here is the basic HTTP Server usage

public class RequestHandler : IHttpRequestHandler
{
    public void Request(HttpServer server, HttpRequest request, HttpResponse response)
    {
        response.SetToHtml();
        response.Write("Hello World!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        RequestHandler handler = new RequestHandler();
        HttpServer server = HttpServer.CreateHttp(handler);
        server.Start(false);
    }
}

Rim MVC

Rim.Mvc library can be used in any project types. Here is a simple and sample code for initializing Rim MVC

using (RimMvc mvc = new RimMvc())
{
    mvc.Init();
    mvc.Run();
}

When you run this code, in same assembly (or referenced assemblies) all RimControllers are added into Rim HTTP Server and it starts to listen HTTP Requests. Sample controller code seems like this

[Route("api/[controller]")]
public class SimleController : RimController
{
    [HttpGet("go/{?id}")]
    public IActionResult Go(int? id)
    {
        return String("Go !");
    }

    [HttpPost("[action]")]
    public IActionResult Post([FromBody] SampleModel model)
    {
        return Json(model);
    }
}

Rim MVC Authorization and Rim JWT

Rim MVC supports authorization with Authorize attribute. You can also create policies for authorization.
Here is simple code for Authentication and Authorization using Rim.Mvc.Auth.Jwt library and some basic policies.

Initialization

using (RimMvc mvc = new RimMvc())
{
    mvc.Init(rim =>
        {
            rim.Services.Add<IDemoService, DemoService>();
	
            rim.AddJwt(options =>
            {
                options.Key = "Very_very_secret_key";
                options.Lifetime = TimeSpan.FromHours(1);
                options.ValidateLifetime = true;
            });
	
            rim.Policies.Add(Policy.RequireRole("PolicyName", "Admin"));
        });
    mvc.Run();
}

Sample Controller

[Route("api/[controller]")]
public class SimleController : RimController
{
    [HttpGet("go/{?id}")]
    [Authorize(Roles = "Role1,Role2")]
    public IActionResult Go(int? id)
    {
        return String("Go !");
    }

    [HttpPost("[action]")]
    [Authorize("PolicyName")]
    public IActionResult Post([FromBody] SampleModel model)
    {
        return Json(model);
    }
}