Skip to content
This repository was archived by the owner on Aug 3, 2018. It is now read-only.

6. Fun Part (SignalR)

Wiley Hilton edited this page Mar 30, 2018 · 2 revisions

SignalR Packages Setup

In visual studios right click the solution in the solution explorer and open "Nuget Package Manager". While on the "Browse" tab search for "Microsoft.AspNet.SignalR". There should be a package that matches the searched string download that package.

Once that installs add a new file ~/Models/Hub.cs. This file controls all connections to the server and what gets sent to who. The contents of that file should be:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace Example.Models
{
	public class ChatHub : Hub
	{
		// Sends the passed in from / message to all other clients
		public void Send(string from, string message)
		{
			Clients.Others.addMessage(from, message);
		}
	}
}

You'll also need a ~/Startup.cs file. This file runs once to setup the hubs.

using Owin;
using Microsoft.Owin;

[assembly: OwinStartup(typeof(Example.Startup))]
namespace Example
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Now, back at base.jsx add this to the top of the page:

import { addMessage } from './actions';

global.hub = $.connection.chatHub;
global.hub.client.addMessage = (from, message) => {
    store.dispatch(addMessage({from, message}))
};
$.connection.hub.start();

Note: There is a hundred ways to manage the connection, this is the simplest (and maybe the worst) but we will be changing to middleware later.

Sending Messages to the Server

On the messageManager.jsx's submit function change it to:

var msg = {
    from: "Me", // Could be any string
    message: this.refs.input.value // This grabs the value of the input reference
}
global.hub.server.send(msg.from, msg.message);
this.props.add(msg);

Testing

Webpack, run/refresh. Now you can open multiple tabs and send messages between them.

The commit I pushed with this is: b821a9f24a7abf684bde30ec4caa4a691bcf55c9

Clone this wiki locally