XSockets.NET - Version5

Your first controller

In the previous section "Getting started" we used the generic controller that is shipped with XSockets. Now we will create our own controller with the same functionality as the generic controller.

What is a controller?

A controller can be compared to a MVC controller, but there is a very big difference. In XSockets we have state in the controller, this means that each client has its own instance of the controller. Thanks to state it is really simple to target subset of connected clients based on the state of each client. This might feel a bit abstract, but is very easy and powerful once you get the idea.

Add a new controller

Right click the project and choose Add -> New Item (or use ctrl + shif + n). Then choose the XSockets.NET 5 section in the templates and select the controller template.

start server

This will give you this code

using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using XSockets.Core.Common.Socket.Event.Interface;

namespace Sample1
{
    /// <summary>
    /// Implement/Override your custom actionmethods, events etc in this real-time MVC controller
    /// </summary>
    public class MyController : XSocketController
    {
        /// <summary>
        /// This will broadcast any message to all clients
        /// connected to this controller.
        /// To use Pub/Sub replace InvokeToAll with PublishToAll
        /// </summary>
        /// <param name="message"></param>
        public override async Task OnMessage(IMessage message)
        {
            await this.InvokeToAll(message);
        }
    }
}

The code above will provide what we call simple messaging, there is no sophisticated logic involved nor any model binding.

In the sample above we broadcast all incoming messages to all clients that is connected to our controller. This is done by using InvokeToAll, all invoke extensions use RPC / RMI. Broadcasting can be a security issue and waste of resources, therefor you can also use InvokeTo to get fine grained control over who you send the message to.