Introduction To WebSockets and SignalR
Posted By : Rudhishthir Prakash | 24-Sep-2017
Web sockets are needed if we are going to create a truly interactive site, the server needs to be able to update the client.
Features:
1. W3C introduced Web Sockets as part of HTML5.
2. Using sockets, clients can call upto the server and the servers can call down to the client.
3. It uses basic messaging system which is similar to web workers.
4. It is supported by most of the browsers.
*****Client side*****
//create the socket var socket = new WebSocket('url'); //receive message from server socket.onmessage = function(e){ $('#output').append('<li>' + e.data + '</li>'); } socket.onopen = function(){ $('#send-message').removeAttr('disabled'); } //send a message socket.send('Hello world');
Web sockets are pretty rudimentary
1. One method(send) to send messages.
2. One event(onmessage) to receive messages.
3. You are responsible for handling the serialization if you are using objects.
4. No fallback if the browser does not support web sockets.
Therefore, a new technology comes into play.
SignalR
SignalR is an ASP.Net technology and it is designed to abstract all of the above drawbacks away and really just allow us to program like we are used to programming.
So, few things to be noticed here will be:
1. Full-blown objects.
2. Full-blown methods.
3. Automatic serialization.
4. Automatic fallback.
*****Server side(C#.Net)*****
using Microsoft.AspNet.SignalR; using System; namespace SocketsDemo { public class MessageHub: Hub { public void ProcessMessage(string message) { //Calls a javascript function Clients.All.MessageProcessed(message + " Processed!!"); } } }
*****Client side*****
var messageHub = $.connection.messageHub; messageHub.client.messageProcessed = function(message){ $('#output').append('<li>' + message + '</li>'); } $.connection.hub.start().done(function(){ //enable button $('#send-message').removeAttr('disabled'); $('#send-message').click(function(){ var message = $('#message').val(); //send that message to the server //Call the ProcessMessage method on the server messageHub.server.processMessage(message); }); });
Request for Proposal
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rudhishthir Prakash
Rudhishthir is a technical enthusiast having experience in C#.NET, NodeJS & various front-end technologies. He has great experience in building quality applications with innovative ideas. He also has proven expertise in handling clients.