Chat Server and Chat Client

Published on by Inno Design

Hi. Today we gonna show you how you can make your own chat application using TCP and UDP protocols.

This will be based on server client architecture. The basic work flow will be as given below

imageThe basic working of this model is as given below

  1. Client sent a message to server that contains two information,  Address of destination and the message to send.
  2. Client send this message to server on the port 8080 (shown here you can take any one which is available to use)
  3. Server looks for destination address and forward message to destination on port 8085(shown here you can take any one which is available to use).
  4. Destination which is another client get this message as it keep on listening to the port num 8085

So hope by now you have learnt the basic processing of the program. So here are the resources to be used

  • .Net Framework 2.0
  • Language c#
  • Development Platform Visual Studio 2008

So let’s start from Designing Windows.

SERVER:

  • Create a new project, name it Chat Server
  • Drop a ListBox into the Form created by Default.
  • Drop a Lable and set Text property to, Connected Member.
  • From the properties bar choose Form1( or whatever you named the first form)
  • Go to Event Double click on Load event.
  • This is How it should Look Like image

 

Now we can start the game “Coding”.

Using statements are as

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

Define Following Variables as Class variables ie out side any function.

delegate void connect(object obj); /* This is delegate for adding connection to our List Box*/
UdpClient up_send = new UdpClient(1024);/* this is our Udp Client For sending Texts
string word;
bool showcon = true;/* this bool variable to show whether Connection is needed*/
static int recieveport; /* this is the Port number of Client which is sending message*/
string msg = “”;/* this is the receive message from Client*/
int senderport; /* this is port num of client which will receive message*/

recieveport and senderport is not as such required, this will become necessary when you will make two client for the same pc mean for testing the project on your pc only not on LAN.

In the Constructor add following Codes

InitializeComponent();// this method will initialize all controls used
Thread serverthread = new Thread(new ThreadStart(server)); /* this is our server thread which will keep on running continuously*/
serverthread.Start();  //Here we started our server thread

Server thread is an Object of a thread that takes a method “server” as a parameter of Threadstart, When this thread will start running the method “server” will start executing

here’s the methode “Server”( make sure the return type of parameter of thread it should be void only)

private void server()
{
UdpClient up_recieve = new UdpClient(8080);/* this is udp client for Listening to client’s message*/
while (true)/* an infinite while loop for keep on checking for new message*/
{
IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any, 0);/* this will give u the connection which is established*?
byte[] recievebyte = up_recieve.Receive(ref remoteipendpoint);/* here’ we re getting the message in Bytes*/
word = Encoding.ASCII.GetString(recievebyte);/* here we converted our message into string, ready to send to destination client*/
recieveport =Convert.ToInt32(word.Substring(0,4));/* here we get  the port number of destination Client, This is for only if you are testing two client on the same pc, you can send Ip address and port number of client instead of just port number*/
if (lstbxMsg.InvokeRequired&& showcon)/* here we are checking whether current thread can access list box or not. it won’t as lstBox is not defined under scope of this thread*/
{
connect con = new connect(connectmem);/* here we made an object of our delegate*/
lstbxMsg.BeginInvoke(con, remoteipendpoint);/*connectmem method will be able to access llistbox as we have given object of delegate of this method as a object of begine invoke method*/
showcon=false;/* we made the connection so make it false*/
}
if(!string.IsNullOrEmpty(word))/* checking whether the received message is empty*/
{
Thread thrdsend = new Thread(new ThreadStart(send));
thrdsend.Start();/* if not then this thread will send the message*/
}
}
}

Here’s the method to insert connected member into List Box

void connectmem(object obj)
{
IPEndPoint remote = (IPEndPoint)obj;
lstbxMsg.Items.Add(remote.ToString()+” Connected”);
}

Here’s our Send method

private void send()
{
byte[] sendbyte = Encoding.ASCII.GetBytes(word);
up_send.Connect(“localhost”, recieveport);
up_send.Send(sendbyte, sendbyte.Length);
}

In first line we taken the message as Byte which will be sent to another client.

In second line we made connection to another client. In our case we have run server and two client on the same pc hence instead of giving any IP address we have taken “localhost”. If you are testing it on LAN then you will have to send message from Client that include destination’s IP address and use the IP address to connect from this statement.

In Third statement we are sending message using the UDP client defined as class variable.

So by now we are Completed with our server that is able to send and receive texts.

Now we will create Our Chat Client. I’ll explain you you file sharing Module of this project in later Blog.

Client:

Let’s start With designing.

  • Create a New Project name it Chat Client
  • Drag and drop a list box, a textbox and a Button into form
  • This should Look Like

Chat Client

Let start game again “Coding”

Using statements are as

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

Define following as Server variables

UdpClient up = new UdpClient(8582);
delegate void connect(object obj);
Thread thrd;

up is our UDP Client for sending data, hence we will send data from port number 8582

The form Load event should be like this

private void Form1_Load(object sender, EventArgs e)
{
thrd = new Thread(new ThreadStart(recieve));
thrd.Start();
}

Here we started our thread for receiving message. this thread will be like receiving thread of server.

Here’s our Receive method

void recieve()
{
UdpClient up = new UdpClient(8085);
while (true)
{
IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any, 0);
byte[] recievebyte = up.Receive(ref remoteipendpoint);
string word = Encoding.ASCII.GetString(recievebyte);
if (lstbxMsg.InvokeRequired)
{
connect con = new connect(connectmem);
lstbxMsg.BeginInvoke(con,remoteipendpoint.ToString()+” “+word);
}
}
}

this method is exactly same as the one of server. remoteipendpoint is IP address of the pc from where the message is coming from. In our Case server.

In server we were inserting connected member into listBox, here will add message.

for adding message the method is as given below

void connectmem(object obj)
{
lstbxMsg.Items.Add(obj.ToString());
}

This is quite understandable

On click event of Button we will send our message to server

the click event will be like this

private void btnSend_Click(object sender, EventArgs e)
{
byte[] sendbyte = Encoding.ASCII.GetBytes(“8086″+textBox1.Text);
up.Connect(“localhost”, 8080);
up.Send(sendbyte, sendbyte.Length);
lstbxMsg.Items.Add(textBox1.Text);
textBox1.Text = “”;
}

This quite same as the sending method of server

1st converting message to byte and connecting to server(in server we were connecting to client) and then sending the message and adding that message to list box as well so that the user will be able to see his/ her own message. the thing to notice here is that we are adding 8086 port number here, You should add IP address of the client to whom user is going to send the message (if you are using LAN).

Here we are completed our Chat client and chat Server.

Isn’t it easy????

Hope you liked it. In next post we will describe File Sharing using TCP.

Please Revert Back in case of any question and help

Published on Networking

Comment on this post