How to create chat application using microsoft asp.net signalr


open visual studio and create a new MVC application image
Select Empty MVC application
image
Open Package Manager Console and install SignalR
image
Right click on project and add new class ChatHub and inherit from 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);
        }
    }
Right click on project and add new class named Startup and add 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>

No comments:

Post a Comment