Showing posts with label chat c#. Show all posts
Showing posts with label chat c#. Show all posts

Thursday, February 20, 2014

Send client message to server using SignalR method - Realtime Chat application on web in ASP.Net: Step 3

This will be my 3rd post on SignalR technology. In previous post I shown how to get server time using SignalR client method, which will be called from server side. Now I shall show how to transfer data between server and client.

This is very simple solution and it can do as same way as normal .Net method calling with parameter.

I am not explaining these code again as I did it last time.

Startup.cs

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

ChatHub.cs file code:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        /// <summary>
        /// getservertime
        /// </summary>
        public void getservertime()
        {
            Clients.Caller.serverresponse("This is server response. Server is calling client method from server. <br/> Server time is: " + DateTime.Now.ToShortTimeString());
        }

        public void sendmessage(string usermessage)
        {
            Clients.Caller.serverresponse(usermessage + " :This is server message <br/>");
        }
    }
}
In this code I have added new method "sendmessage(parameter1)" and it will call same client method to return data to client. This is very simple code.


Next will come HTML part, which is as below:




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <!--Reference the jQuery library. -->
    <script src="Scripts/json2.js"></script>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
   
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
   
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
   
    <script type="text/javascript">
$(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;


    //Write your server response related code here
    chat.client.serverresponse = function (message) {
        $('#dvServerResponse').append(message);
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        //Write your server invoke related code here
        $('#btnHello').click(function () {
            console.log('call server');
            chat.server.sendmessage($('#txt').val());
        });
    });
});
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
<div>
    Enter your message: <input type="text" id="txt" /><br />
    <input type="button" id="btnHello" value="Send message to server" />   

    <div id="dvServerResponse"></div>   
   
</div>
    </div>
    </form>
</body>
</html>
When you will run this in browser it will show as below:


Hope you have enjoyed this post and please visit my blog again.

Next will show something about Lamda Expression which I shall use in my chat application.



Tuesday, February 18, 2014

SignalR - Hello World: Real time chat application on Web in ASP.Net using SignalR technology : Step 1


Programming with distributed technology is my passion. Earlier I have worked with Remoting, Socket, Web Service and a bit with WCF. So when I first came to know about SignalR technolog, really I can not wait to start coding on it. Now I can able to write own chat application for AlapMe and really its working fine. Most of all by using SignalR I can use socket of HTML5. I shall write multiple posts on SignalR as tutorial as I did in past with C# Socket programming. I shall publish these posts on this blog and on my socket programming blog as well.
I have started SignalR programming with Visual Studio Express 2013 which is freely downloadable from here. Also you can read full documentation from Microsoft from this link. As my target to share some practical example with ready to use code hence I shall not describe in detail about the technology. You can follow Microsoft documentation website for it.
To start with SignalR first coding you need to follow steps are below.
Lunch your VS 2013 and create a blank project and add new item of SignalR Hub Class (v2) set its name as you wish, for my case its MyHub.cs. When you will add this class Visual Studio automatically add all related references and jquery classes. To add these things it may take some time may be 2-3 minutes. This new item will come with a sample method 'Hello()', for now just follow these later I shall describe what is these things and why these are. Full code will look like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalR_Learning
{
    public class MyHub : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}
Now go to next step and add next item in project, that is OWIN Startup class. I am giving its default name 'Startup1.cs' for my sample project. Visual Studio will create this file with some pre-added code. We will extend these code as per your needs. Code as below:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalR_Learning.Startup1))]
namespace SignalR_Learning
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }
    }
}
In method Configuration I shall add just a line of code 'app.MapSignalR();' so full method will look like:
public void Configuration(IAppBuilder app)
{
    // For more information on how to configure your application, visit      http://go.microsoft.com/fwlink/?LinkID=316888
    app.MapSignalR();
}
 Now we will move to front end coding and this part will develop with simple HTML page, however you can use ASPX page as well. Now I have added a HTML page with name 'index.html'
<! DOC TYPE ht ml >
< ht ml xmlns="http://www.w3.org/1999/xhtml" >
    SignalR Simple Chat
    "X-UA-Compatible" content="IE=edge" / >
    
    
     < sc ript src="Scripts/jquery-1.10.2.js">
    < sc ript src="Scripts/jquery-1.10.2.min.js">
   
    < scri pt src="Scripts/json2.js">
    
    "Scripts/jquery.signalR-2.0.0.js">
    "Scripts/jquery.signalR-2.0.0.min.js">
    
    "/signalr/hubs">
    
    "text/ ">
        var chat;
        $(f unction () {
            // Declare a proxy to reference the hub.
            //chat = $.hubConnection.myhub;
            chat = $.connection.myhub;
            //alert(chat);
            chat.client.hello = function (message) {
                alert(message);
            };
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#btnhello').click(function () {                   
                    alert(chat);
                });
            });
        });
    

    "button" value="Hello" id="btn hello" />



 
 


Saturday, October 20, 2012

Send File from Server to Client using C# Socket Programming 6/6



Server codes are here...



Server code:


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace beginSocketServer
{
//FILE TRANSFER USING C#.NET SOCKET - SERVER
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("That program can transfer small file. I've test up to 850kb file");
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
//clientSock is the socket object of client, so we can use it now to transfer data to client
Socket clientSock = sock.Accept();


string fileName = "test.txt";// "Your File Name";
string filePath = @"C:\FT\";//Your File Path;
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);

byte[] fileData = File.ReadAllBytes(filePath + fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);


clientSock.Send(clientData);
Console.WriteLine("File:{0} has been sent.", fileName);


clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("File Receiving fail." + ex.Message);
}
}
}
}

Send File from Server to Client using C# Socket Programming 4/6



6) Client Action: This section of code is retrieving file name length and by using this file name which was sent by server at the starting of file data. This will require retrieving file name.


int fileNameLen = BitConverter.ToInt32(clientData, 0);

string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);


7) Client Action: Now received data is saving at client side by using below lines of code with the help of binary stream writer.


BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append));

bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);


Here file data is starting to retrieve after file size and file name bytes. This has managed in 2nd line.


By that way one small file can be sent from server to client.


8) Client and Server Action: Now server and client both will do same activity; that is to release server and client socket by using close method of socket. Client needs to close binary stream writer as well.


So by following these steps a file can be sent from server to client. Same way we can send large file from server to client. TCP buffer can not handle large data size at a time. So if you try to send large file it will throw overflow error. To avoid this error you need to slice big file in small pieces (same thing has applied in 2GB file transfer article) and need to send one by one slice. So there will be loop to send file from server to client that means step 5 to step 7 will repeat.


Also server can send some particular file based on client request. But for that client need to send file name at the time of server request. So server can search file based on this information, so can read and send particular file to client.


By handling multiple clients objects one server can send file to multiple clients simultaneously but for that you need to create multithread application and need to keep track client socket object array with data file. So programming must be more complex. I am planning to write codes up to multiple client to client large file transfer with the help of one server application step by step. So keep watching my blog to learn new things.


Download this project from below link:

https://rapidshare.com/files/691859425/Client and Server - Send Small File from Server to Client.zip  



Send File from Server to Client using C# Socket Programming 2/6



2) Client Action: Now turn is coming to client to request server.


IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");

IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);

Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);


clientSock.Connect(ipEnd);


These codes are from client application, here first two lines are using to get Localhost IP address and by using this creating new IPEnd point. Be sure there IP address and port number must be same as server address. I am running my applications in same machine so using localhost.


Next two lines of code is creating a socket object and trying to connect by using IPEnd point. So this socket object will try to connect server socket which was in listen mode.


3) Server Action: Again turn comes to server about to response on client’s request and this is doing by below line of code in server application:


Socket clientSock = sock.Accept();


This “sock” is server socket object which was created previously and it was in listen mode. This sock object will accept client request and generate a new socket object with name “clientSock”. Rest all work in server side will be performed by “clientSock” object to handle this particular client request.



Tuesday, August 18, 2009

Global Text Chat Room Application using C#.Net Programming - Remoting technology

The basic and simple architecture of .Net Remoting technology has three parts, these are –
1. Base Remoting class: This is like a bridge to communicate between Client and Server. It exists in a DLL file which shares Server and Client program.
2. Server class: It is server to server Client requests, every client connect to Server to communicate each other. This program holds a Remoting class’s DLL.
3. Client class: This is client part of Remoting architecture. This also holds a copy of Remoting base DLL. It connects to Server and via server communicates to other client.This is very simple idea of Remoting architecture, if you want to learn about this technology then you may read from MSDN site. I am not going to explain about its theory, I am focusing mainly about its application.

Now I will describe about a Global Text Chat Room application using this technology. This is very easy to develop and interesting also. In this program I have not covered about thread related issues, this is very basic type of chat application.



As Remoting architecture here has a base class and after compiling produces a DLL file with name ‘RemoteBase.dll’. This DLL has about six methods like, JoinToChatRoom, LeaveChatRoom, SendMsgToSvr (Send Message To Server), GetMsgFromSvr (Get Message From Server) etc.




Next one is Server, this is a Windows Form (WinForm) application. This application uses ‘RemoteBase.dll’ as its reference file for library. Server registers a TCP channel with a port number. You may choose any port number from 1025 to 65k. And it registers for well known type of RemoteBase and mode type is Singleton. (Remember it should not work for Singlecall type, details and different will found on MSDN).
When you run server you will see a window as attached screen shot and need to press button ‘Start’ to start server and check server status as ‘Running’. To stop the server need to press on ‘Stop’ button.




Last one is Client part, it also a Windows form (WinForm) application with two windows forms. As server client also take reference of ‘RemoteBase.dll’ for library. When you run this client application one popup window will come and ask for your name which will be used to chat room to represent you. Then press on Join button. After that chat room window will open.

There also has server address like ‘tcp://localhost:8080/HelloWorld’ here ‘localhost’ is server address and 8080 is port number. Server address needs to tell where your server is running. I am using server and client in same machine so server address is ‘localhost’ you may give any IP address here. Port number also can be changed but server opening port number and client requesting port number should be same. You can not change reaming thing in address otherwise this chat application will not work.


Chat room window has four sections largest one to see all chat message and below of that to type chat message, and send button to send message to server. Just above list to display all online user.

When you put your name then client application creates a remote base class’s object and connects to server by registering TCP channel. Then connects to Chat Room and seek latest message number. After that main Chat Room window opens. From that window it seeks latest available message in server by a timer. To get message from server it invokes ‘GetMsgFromSvr()’, and get available online user through ‘GetOnlineUser (), and user message sends from client application to server by invoking ‘SendMsgToSvr()’. For better understanding you may go through the code.

Source code as below and full source code can download from following link:

How the code is working

Start the Server:

When users are trying start Server by clicking Start button the following code executes –


private void btnStart_Click(object sender, EventArgs e)

{
if (channel == null)
{
channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(SampleObject), "ChatRoom"WellKnownObjectMode.Singleton);
lblStatus.Text = "Running...";
btnStart.Enabled = false;
btnStop.Enabled = true;
}
}
Here a TcpChannel opens with port number 8080 and register it as WellKnownServiceType. ‘ChatRoom’ it is the ‘ObjectUri’ it will require to connect to server from client.
On the other hand when user press to ‘Stop’ server then unregister the channel and stop the server. Codes are below-
private void btnStop_Click(object sender, EventArgs e)
{
if (channel != null)
{
ChannelServices.UnregisterChannel(channel);
channel = null;
lblStatus.Text = "Stopped.";
btnStart.Enabled = true;
btnStop.Enabled = false;
}

}


Join to ChatRoom:
Next coming the client, how client connect to server and user login to the chat room. To joining to chat room the below codes are executes
private void JoinToChatRoom()
{
if (chan == null && txtName.Text.Trim().Length != 0)
{
chan = new TcpChannel();
ChannelServices.RegisterChannel(chan,false);
// Create an instance of the remote object
objChatWin = new frmChatWin();
objChatWin.remoteObj = (SampleObject)Activator.GetObject(typeof(RemoteBase.SampleObject), txtServerAdd.Text);
if (!objChatWin.remoteObj.JoinToChatRoom(txtName.Text))
{
MessageBox.Show(txtName.Text+ " already joined, please try with different name");
ChannelServices.UnregisterChannel(chan);
chan = null;
objChatWin.Dispose();
return;
}
objChatWin.key = objChatWin.remoteObj.CurrentKeyNo();
objChatWin.yourName= txtName.Text;
this.Hide();
objChatWin.Show();
}
}
Here from user client application takes a name and check to server is the name available or not. If name is available then user gets the ‘CurrentKeyNo’ of server, it is the number of last chat message (how the key generated, describe in later) and open the ChatRoom window.
If user name is already taken by other user, then application asks to user for different name.
In server side to join a user in chat server “JoinToChatRoom()” method invokes, lets see what happens within the method –

public bool JoinToChatRoom(string name)
{
if (alOnlineUser.IndexOf(name) > -1)
return false;
else
{
alOnlineUser.Add(name);
SendMsgToSvr(name + " has joined into chat room.");
return true;
}
}
Here is user can successfully logged in to server then his name is added in a user collection, ‘alOnlineUser’ is it an ArrayList type object.


Send message to server:
When user type some message and press on ‘Send’ button or just press ‘Enter’ button then client application try to send message to server. To do it client call the below method –
private void SendMessage()
{
if (remoteObj != null && txtChatHere.Text.Trim().Length>0)
{
remoteObj.SendMsgToSvr(yourName + " says: " + txtChatHere.Text);
txtChatHere.Text = "";
}
}
Here client application in invokes the “SendMsgToSvr()” method of server. Let’s see the method what doing-
public void SendMsgToSvr(string chatMsgFromUsr)
{
hTChatMsg.Add(++key, chatMsgFromUsr);
}
Wow! This is very small code. Actually this is adding the users’ message to another collection. I have used for this collection of HashTable type, you may use any other collection type to store string data.
See here has one counter ‘key’ which is incrementing by one. This is the counter which is maintaining the chat message number. It will help us to get chat message from server.
Receive Message from Server:
Ok friend, next look at how data are getting from server –
In chat room a timer always fires, which try to get message from server and current available user in server. Here below codes plays in Client side –
private void timer1_Tick(object sender, EventArgs e)
{
if (remoteObj != null)
{
string tempStr = remoteObj.GetMsgFromSvr(key);
if (tempStr.Trim().Length > 0)
{
key++;
txtAllChat.Text = txtAllChat.Text + "\n" + tempStr;
}
ArrayList onlineUser = remoteObj.GetOnlineUser();
lstOnlineUser.DataSource = onlineUser;
skipCounter = 0;
if (onlineUser.Count < 2)
{
txtChatHere.Text = "Please wait untill atleast two user join in Chat Room.";
txtChatHere.Enabled = false;
}
else if(txtChatHere.Text == "Please wait untill atleast two user join in Chat Room." && txtChatHere.Enabled == false)
{
txtChatHere.Text = "";
txtChatHere.Enabled = true;
}
}
}
Here client invokes “GetMsgFromSvr()” method to get message, with parameter key. The codes of the method are –
public string GetMsgFromSvr(int lastKey)
{
if (key > lastKey)
return hTChatMsg[lastKey + 1].ToString();
else
return "";
}
The server just takes the key as last-key of user’s message and uses it in Chat message collection to fetch the next chat message, after that the message return to the client.
To online user client application invokes “GetOnlineUser()” method, lets see what happen in server side within the method.
public ArrayList GetOnlineUser()
{
return alOnlineUser;
}
So this method returns the user collection object which was created in “JoinToChatRoom()” method.

Leave the Chat Room:
When user closes the chat room, then client application request to server to remove his/her name from server’s online user list. In client side the below method invokes –
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (remoteObj != null)
{
remoteObj.LeaveChatRoom(yourName);
txtChatHere.Text = "";
}
Application.Exit();
}
In server side the “LeaveChatRoom()”method invokes, the code of that method is –
public void LeaveChatRoom(string name)
{
alOnlineUser.Remove(name);
SendMsgToSvr(name + " has left the chat room.");
}
Now server has deleted your name from online user list.