Introduction:
Here I will explain how to create chat application in asp.net using c# or how to create chat application using WebSocket. If you want to create simple chat application in asp.net using c# then do following step and you can chat using your chat application.
We can create chat application using Jquery Ajax method, SignalR and WebSocket .
So, Now I explaining how to create chat application in asp.net using c# with WebSocket.

WebSocket:
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
It is two-ways connections
It working only in HTML 5
It’s for real time data app like chat, stock market app and online game

WebSocket – server side:
Asp.net 4.5 and above framework
IIS 8 and above IIS on server

STEP : how to create chat application in asp.net using c#
Now follow this Step by step to create chat application in asp.net using WebSocket

Create new project or website
Add WebSockets.dll in project
Add Class file(MicrosoftwebSockets2.cs) in App_Code file
Add Handler(WebSocketServer2.ashx) file in your project
Add HTML file (index.html)

Now your project solution explorer like below

how to create chat application in asp net using c sharp

Once you add all above files in your project or website then paste below code in your asp.net project.
Open your App_Code/MicrosoftwebSockets2.cs class file and paste following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.WebSockets;

public class MicrosoftwebSockets2 : WebSocketHandler
{
      private static WebSocketCollection clients = new WebSocketCollection();
      private string name;

      public MicrosoftwebSockets2()
      {
//cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
      }

      public override void OnOpen()
      {
           name = this.WebSocketContext.QueryString["name"];
           clients.Add(this);
           clients.Broadcast(name + " has connected.   Total online user:"+clients.Count());
      }

      public override void OnMessage(string message)
      {
           clients.Broadcast(string.Format("{0} : {1} ", name, message));
      }

      public override void OnClose()
      {
           clients.Remove(this);
           clients.Broadcast(string.Format("{0} has gone away ", name));
      }
}

Open your WebSocketServer2.ashx Handler file from root and paste following code

<%@ WebHandler Language="C#" Class="WebSocketServer2" %>

using System;
using System.Web;
using Microsoft.Web.WebSockets;
using System.Web.WebSockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

public class WebSocketServer2 : IHttpHandler
{
      public void ProcessRequest(HttpContext context)
      {
           if (context.IsWebSocketRequest)
           {
                context.AcceptWebSocketRequest(new MicrosoftwebSockets2());
           }
      }

      public bool IsReusable
      {
           get
           {
                return false;
           }
      }
}

Open your index.html file from root and paste following code

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>How to create chat application in asp.net using WebSocket</title>

<a href="http://jquery-1.9.1.js">http://jquery-1.9.1.js</a>

$(document).ready(function () {
     $('#txtMessage').keypress(function (e) {
     if (e.which == 13) {
         ws.send($('#txtMessage').val());
         $('#txtMessage').val('');
         $('#txtMessage').focus();
         return false;
     }
});

var name = prompt('what is your name?:');

//Add your website or project URL here

var url = 'ws://localhost:8945/WebSocketServer2.ashx?name=' + name;
ws = new WebSocket(url);
ws.onopen = function () {
    $('#messages').prepend('Connected </br>');
    $('#cmdSend').click(function () {
        ws.send($('#txtMessage').val());
        $('#txtMessage').val('');
        $('#txtMessage').focus();
    });
};

ws.onmessage = function (e) {
    if (e.data.search(name) == -1) {
        $('#chatMessages').css("color", "green");
    }
    else {
        $('#chatMessages').css("color", "blue");
    }

    $('#chatMessages').prepend(e.data + '</br>');
    $('#txtMessage').focus();
};

$('#cmdLeave').click(function () {
    ws.close();
});

ws.onclose = function () {
   //$('#chatMessages').prepend('Closed</br>');
    $('#chatMessages').prepend(name+ ' - You are Log out. </br>');
};

ws.onerror = function (e) {
    $('#chatMessages').prepend('ERROR - Oops something went wrong </br>');
};

});

</head>

<body>
<br />
<br />

<h1> Chat example in asp.net using webSocket</h1>

<input id="txtMessage" style="width:40%" />

<input id="cmdSend" type="button" value="Send" />

<input id="cmdLeave" type="button" value="Log out" />

<br />

<div id="chatMessages" />

</body>
</html>

Now your chat application is ready to use. Just run your project or website in two different browser and you can chat with your chat application.

If you want to save user chat history that time you can use insert data code in classfile and save it.

Source: http://problemaspdotnet.blogspot.com/2016/05/how-to-create-chat-application-in.html

Advertisements