Socket Programming in C# .Net

Dot Net Programming in C# with source code and DLL file. Covers Socket, Remoting, Stored Procedure, ASP.Net, IO, Web Service, Windows Service, Installer, Console Programming, Win Forms, Web Forms, Ajax, Web publishing, Text Chat, Large File Transfer, File Handling etc.

Download source code from here

Global Text Chat Room Application using C#.Net 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:

For Common class
http://rapidshare.com/files/276755910/GChat_RemoteBase.zip

For Server
http://rapidshare.com/files/276763066/GChat_RemoteServer.zip

For Client
http://rapidshare.com/files/276763176/GChat_RemotingClient.zip

Common class – Remoting Base Class code:

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Collections;

namespace RemoteBase

{

public class SampleObject : MarshalByRefObject

{

Hashtable hTChatMsg=new Hashtable ();

ArrayList alOnlineUser = new ArrayList();

private int key = 0;

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;

}

}

public void LeaveChatRoom(string name)

{

alOnlineUser.Remove(name);

SendMsgToSvr(name + " has left the chat room.");

}

public ArrayList GetOnlineUser()

{

return alOnlineUser;

}

public int CurrentKeyNo()

{

return key;

}

public void SendMsgToSvr(string chatMsgFromUsr)

{

hTChatMsg.Add(++key, chatMsgFromUsr);

}

public string GetMsgFromSvr(int lastKey)

{

if (key > lastKey)

return hTChatMsg[lastKey + 1].ToString();

else

return "";

}

}

}

Server Class code:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using RemoteBase;

namespace RemoteServer

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

TcpChannel channel;

private void btnStart_Click(object sender, EventArgs e)

{

if (channel == null)

{

channel = new TcpChannel(8080);

ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(typeof(SampleObject), "HelloWorld", WellKnownObjectMode.Singleton);

lblStatus.Text = "Running...";

btnStart.Enabled = false;

btnStop.Enabled = true;

}

}

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;

}

}

}

}

Client Class code:

Login form

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Collections;

using RemoteBase;

namespace RemotingClient

{

public partial class frmLogin : Form

{

TcpChannel chan;

ArrayList alOnlineUser = new ArrayList();

frmChatWin objChatWin;

public frmLogin()

{

InitializeComponent();

}

private void btnJoin_Click(object sender, EventArgs e)

{

JoinToChatRoom();

}

private void JoinToChatRoom()

{

if (chan == null && txtName.Text.Trim().Length != 0)

{

chan = new TcpChannel();

ChannelServices.RegisterChannel(chan,false);

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();

}

}

}

}

Chat Window

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Collections;

using RemoteBase;

namespace RemotingClient

{

public partial class frmChatWin : Form

{

internal SampleObject remoteObj;

internal int key = 0;

internal string yourName;

ArrayList alOnlineUser = new ArrayList();

public frmChatWin()

{

InitializeComponent();

}

private void btnSend_Click(object sender, EventArgs e)

{

SendMessage();

}

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;

if (onlineUser.Count <>

{

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;

}

}

}

private void SendMessage()

{

if (remoteObj != null && txtChatHere.Text.Trim().Length>0)

{

remoteObj.SendMsgToSvr(yourName + " says: " + txtChatHere.Text);

txtChatHere.Text = "";

}

}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)

{

if (remoteObj != null)

{

remoteObj.LeaveChatRoom(yourName);

txtChatHere.Text = "";

}

Application.Exit();

}

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)

{

System.Diagnostics.Process.Start("iexplore.exe", "http://socketprogramming.blogspot.com");

}

}

}


Labels: , , , ,

Global Text Chat Room Application using C#.Net 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:

For Common class
http://rapidshare.com/files/276755910/GChat_RemoteBase.zip

For Server
http://rapidshare.com/files/276763066/GChat_RemoteServer.zip

For Client
http://rapidshare.com/files/276763176/GChat_RemotingClient.zip

Common class – Remoting Base Class code:

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Collections;

namespace RemoteBase

{

public class SampleObject : MarshalByRefObject

{

Hashtable hTChatMsg=new Hashtable ();

ArrayList alOnlineUser = new ArrayList();

private int key = 0;

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;

}

}

public void LeaveChatRoom(string name)

{

alOnlineUser.Remove(name);

SendMsgToSvr(name + " has left the chat room.");

}

public ArrayList GetOnlineUser()

{

return alOnlineUser;

}

public int CurrentKeyNo()

{

return key;

}

public void SendMsgToSvr(string chatMsgFromUsr)

{

hTChatMsg.Add(++key, chatMsgFromUsr);

}

public string GetMsgFromSvr(int lastKey)

{

if (key > lastKey)

return hTChatMsg[lastKey + 1].ToString();

else

return "";

}

}

}

Server Class code:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using RemoteBase;

namespace RemoteServer

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

TcpChannel channel;

private void btnStart_Click(object sender, EventArgs e)

{

if (channel == null)

{

channel = new TcpChannel(8080);

ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(typeof(SampleObject), "HelloWorld", WellKnownObjectMode.Singleton);

lblStatus.Text = "Running...";

btnStart.Enabled = false;

btnStop.Enabled = true;

}

}

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;

}

}

}

}

Client Class code:

Login form

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Collections;

using RemoteBase;

namespace RemotingClient

{

public partial class frmLogin : Form

{

TcpChannel chan;

ArrayList alOnlineUser = new ArrayList();

frmChatWin objChatWin;

public frmLogin()

{

InitializeComponent();

}

private void btnJoin_Click(object sender, EventArgs e)

{

JoinToChatRoom();

}

private void JoinToChatRoom()

{

if (chan == null && txtName.Text.Trim().Length != 0)

{

chan = new TcpChannel();

ChannelServices.RegisterChannel(chan,false);

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();

}

}

}

}

Chat Window

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Collections;

using RemoteBase;

namespace RemotingClient

{

public partial class frmChatWin : Form

{

internal SampleObject remoteObj;

internal int key = 0;

internal string yourName;

ArrayList alOnlineUser = new ArrayList();

public frmChatWin()

{

InitializeComponent();

}

private void btnSend_Click(object sender, EventArgs e)

{

SendMessage();

}

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;

if (onlineUser.Count <>

{

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;

}

}

}

private void SendMessage()

{

if (remoteObj != null && txtChatHere.Text.Trim().Length>0)

{

remoteObj.SendMsgToSvr(yourName + " says: " + txtChatHere.Text);

txtChatHere.Text = "";

}

}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)

{

if (remoteObj != null)

{

remoteObj.LeaveChatRoom(yourName);

txtChatHere.Text = "";

}

Application.Exit();

}

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)

{

System.Diagnostics.Process.Start("iexplore.exe", "http://socketprogramming.blogspot.com");

}

}

}


Labels: , , , ,

  1. Blogger sanjay | August 24, 2009 6:15 AM |  

    it helps me alot for understanding the socket programming and to do my project....

leave a response