Showing posts with label chat source code. Show all posts
Showing posts with label chat source code. Show all posts

Saturday, October 20, 2012

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  



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.

Thursday, September 20, 2007

Server Socket Programming in C#, how to start

For beginner socket is quite complicated. But it's not very hard to learn. Basically I've learned it within few hours. So I believe it can learn any body. However let's start.

Socket programming have two part
I. Server
II. Client.

I. Server:
To start server need to follow some steps, these are:
i. First create a IPEndPoint
[e.g. IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);]

ii. Create a socket object.
[Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);]

iii. Bind socket with IPEndPoint.
[sock.Bind(ipEnd);]

iv. Place socket in Listen mode (to accept call of client)
[sock.Listen(maxClientReceived);]

v. When any call comes from client Accept that call.
[Socket clientSock = sock.Accept();]
At that position Accept() return a new socket to continue communication with called client. By that socket Client-Server communication continue.

To send some data (in byte array form) to client from server just write
clientSock.send(byteArrayData);

To receive client data just write
int receivedLen= clientSock.Receive(clientData);
Receive() function reads data in byte array form from client socket and writes to 'clientData' array, and return integer value how much bytes has received.

I'm giving complete code of a simple server socket below:-


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace beginSocketServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
string clientDataInString = Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
Console.WriteLine("Received Data {0}", clientDataInString);
string clientStr = "Client Data Received";
byte[] sendData = new byte[1024];
sendData= Encoding.ASCII.GetBytes(clientStr);
clientSock.Send(sendData);
clientSock.Close();
Console.ReadLine();
}
}
}


To run that server code you don't need to write client code just open a webbrowser and write (I've use Mozilla Firefox 2.0.0.7) :
http://localhost:5656/

Server console output was:

Received Data GET / HTTP/1.1Host: localhost:5656User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,
*/*;q=0.5Accept-Language: en-us,en;q=0.5Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-alive

And in web browser output was:Client Data Received.

Ok, Simple server socket application has done. Next will give simple client socket application for beginner.


see more