Monday, August 17, 2009

Making Threads in C#

Threads are means of splitting your program into two or more programs that execute parallel to each other. A simple code for making threads in C# (.NET) is written below. When we write this code, our main program will continue its execution from the end of this code, but before that it will create another process/program that will execute a function whose name will be written as explained below.

On top of the page write down the following:

using System.Threading;

// This will act like including a header file which deals with threads

Now to make a thread, write down the following:

Thread T = new Thread(new ThreadStart( /* Name Of Function */ ));

// Replace the text /* Name Of Function */ by the name of function that you want your newly made thread to execute

// Now your thread has been created but has not started its execution yet

T.Start();

// Write this command and the thread will start its execution

// Another command that is used with threads is:

T.Join();

// With this command the thread T will wait till all the previously created threads to finish their execution, before T will start its own execution

The same code can be written inside a for loop and any number of threads can be created.

File Transfer between Client and Server

Sender’s Code

Write the following using statements if they are not initially written:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

Now write the following function/code (tried and tested in a console application) :

try
{
IPAddress ipAddress = IPAddress.Parse(” /* IP Address of receiver */ “);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, 8001);
Socket clientSock = new Socket(AddressFamily.InterNetwork,

SocketType.Stream, ProtocolType.IP);

string fileName = ” /* Name Of File */ “;

// Write the name of the file along with its extension above
string filePath = @” /* Path Of File */ “;

// Write the path of the file here e.g “D:/Projects”


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.Connect(ipEnd);
Console.WriteLine(”Sending File {0}”, fileName);
clientSock.Send(clientData);
// The file has been sent


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

———————————————————————————————————————————————————————-

Receiver’s Code

Write the following using statements if they are not initially written:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

Now write the following function/code (tried and tested in a console application) :

try
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8001);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(8001);
Socket clientSock = sock.Accept();

byte[] clientData = new byte[1024 * 5000];
string receivedPath = “”;

int receivedBytesLen = clientSock.Receive(clientData);

int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen – 4 – fileNameLen);

// The file has been received

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

Message Transfer between Server and Client

This code can be used to transfer messages between a client and a server. This client server are two applications running upon the same computer, or multiple computers connected over a network. Changing the IP address within the code to your own computer’s IP address will initiate the communication between the client server of the same computer.

IP address can be found by going to Start->Run, then type cmd and press enter to enter the command prompt. After this type ipconfig in the command prompt and press enter and the IP address of your computer will be displayed.

Client Code

Write the following using statements if they are not initially written:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

Now write the following code (tried and tested in a console application) :

try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(” /* IP Address of Server */”, 8001);

// use the IP address as in the server program

Console.WriteLine(”Connected”);
Console.Write(”Enter the string to be send : “);

String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();

ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine(”Transmitting…..”);

stm.Write(ba, 0, ba.Length);

// The string has been transmitted but we are waiting for an acknowledgement from the server telling us that the message has been successfully received.

byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);

for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));

// The acknowledgment has been received and displayed

tcpclnt.Close();
}

catch (Exception e)
{
Console.WriteLine(”Error: ” + e.StackTrace);
}

Note that these try catch statements are written because they are already created functions present within the C# compiler that catch the exceptions, and perform the exception handling for us. However they do not catch every possible exception, but still they catch a lot of exceptions to be used as good programming practises.

—————————————————————————————————————————————————————————-

Server Code

Write the following using statements if they are not initially written:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;

Now write the following code (tried and tested in a console application) :

try
{
IPAddress ipAd = IPAddress.Parse(” /*IP Address of client */ “);
TcpListener myList=new TcpListener(ipAd,8001);

myList.Start();
// The server is waiting for incoming client connections

Socket s=myList.AcceptSocket();

// The connection has been established

byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine(”Recieved…”);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));

// The message has been received

ASCIIEncoding asen=new ASCIIEncoding();

s.Send(asen.GetBytes(”The string was recieved by the server.”));
// The acknowledgement has been sent

s.Close();
myList.Stop();

}

catch (Exception e)
{
Console.WriteLine(”Error….. ” + e.StackTrace);
}

If this code is being used in different computers, then make sure that your firewall is turned off and the computers are connected within a secure network (for all the rights of the connection to be granted).