How to create chat application using microsoft asp.net signalr

In this post, I will show you how to create a simple chat application using the Microsoft SignalR framework

Step1

open visual studio and create a new MVC application image

Step2

Select Empty MVC application


image

Step3

Open Package Manager Console and install SignalR


image

Step4

Right-click on the project and add a new class ChatHub and inherit from the Hub class that resides in

  Microsoft.AspNet.SignalR


image

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
            Clients.All.newMessage(message);
        }
    }

Step5

Right-click on the project and add a new class named Startup and add the following code inside it

 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }

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="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <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>
    <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 () {
                    chatHub.server.sendMessage($("#txtMessage").val());
                });

            });

        });
    </script>
</head>
<body>
    <label for="txtMessage">Message</label>
    <input type="text" name="txtMessage" id="txtMessage" />
    <input type="button" value="send" id="btnSend" />
    <hr />
    <ul id="messages"></ul>
</body>
</html>

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم