How to create chat application using microsoft signalr

open visual studio and create a new MVC application image
Select Empty MVC application
Open Package Manager Console and install SignalR
Right click on project and add new class ChatHub and inherit from Hub class that resides in Microsoft.AspNet.SignalR
public class ChatHub:Hub
       //this method is called when client send message
        public void sendMessage(string message)
           //this method brodcast message to all connected client
Right click on project and add new class named Startup and add following code inside it
 public class Startup
        public void Configuration(IAppBuilder app)
Create a new html page and add following markup inside it.You can see that I have added three JavaScript lib :jquery,jqery-signalr* and  signalr/hubs.Signalr/hubs contains functions for interacting with server side hub class and also it generated automatically by signalr framework
<!DOCTYPE html>
<html xmlns="">
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="signalr/hubs"></script>
        $(document).ready(function () {
            var chatHub = $.connection.chatHub;
            chatHub.client.newMessage = function (data) {
                $("#messages").append("<li>" + data + "</li>");
            chatHub.connection.start().done(function () {
                $("#btnSend").click(function () {


    <label for="txtMessage">Message</label>
    <input type="text" name="txtMessage" id="txtMessage" />
    <input type="button" value="send" id="btnSend" />
    <hr />
    <ul id="messages"></ul>

No comments:

Post a Comment