Thursday, 31 October 2013

C# - Create a Chat Application Client - Server







In this article we are going to see how to create a chat application using C#, for this we have to create a two projects in Console Applications one for client and another for server.

please dis-connet the internet while checking with this code.

Server:

First Let we see about Server, Which will get the request from client .Get the IP address of the Server Machine and Get the username and Port at which server has to watch for request.Socket is the used to receive and accept the request in TCP as stream.

C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ChatServer
{
    class Program
    {
        static Socket soc;
        static Socket acc;
        static int port = 9000;
        static IPAddress ip;
        static Thread rec;
        static string name;

        static string GetIp()
        {
            string hostname = Dns.GetHostName();
            IPHostEntry ipentry = Dns.GetHostEntry(hostname);
            IPAddress[] addr = ipentry.AddressList;
            return addr[addr.Length - 1].ToString();
        }


        static void RecV()
        {
            while (true)
            {
                Thread.Sleep(500);
                byte[] buffer = new byte[300];
                int rece = acc.Receive(buffer, 0, buffer.Length, 0);
                Array.Resize(ref buffer, rece);
                Console.WriteLine(Encoding.Default.GetString(buffer));
            }
        }



        static void Main(string[] args)
        {
            rec = new Thread(RecV);
            Console.WriteLine("Your Local Ip is " + GetIp());
            Console.WriteLine("Please enter your name");
            name = Console.ReadLine();
            Console.WriteLine("Please enter HostPort");
            string prt = Console.ReadLine();

            try
            {
                port = Convert.ToInt32(prt);
            }
            catch
            {
                port = 9000;
            }

            ip = IPAddress.Parse(GetIp());
            soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soc.Bind(new IPEndPoint(ip, port));
            soc.Listen(0);
            acc = soc.Accept();
            rec.Start();
            while (true)
            {
                byte[] sdata = Encoding.Default.GetBytes("<"+name+">"+Console.ReadLine());
                acc.Send(sdata, 0, sdata.Length, 0);
            }


        }
    }
}



Client :

Now we see for the client same steps , but difference is here is send is the request we are make a separate thread for see the message from server.

C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ChatClient
{
    class Program
    {
        static string name;
        static int port = 9000;
        static IPAddress ip;
        static Socket soc;
        static Thread rec;


        static string GetIp()
        {
            string hostname = Dns.GetHostName();
            IPHostEntry ipentry = Dns.GetHostEntry(hostname);
            IPAddress[] addr = ipentry.AddressList;
            return addr[addr.Length - 1].ToString();
        }

        static void RecV()
        {
            while (true)
            {
                Thread.Sleep(500);
                byte[] buffer = new byte[300];
                int rece = soc.Receive(buffer, 0, buffer.Length, 0);
                Array.Resize(ref buffer, rece);
                Console.WriteLine(Encoding.Default.GetString(buffer));
            }
        }

       

        static void Main(string[] args)
        {
            rec = new Thread(RecV);
            Console.WriteLine("Please enter your name");
            name = Console.ReadLine();
            ip = IPAddress.Parse(GetIp());
            Console.WriteLine("Please enter HostPort");
            string prt = Console.ReadLine();

            try
            {
                port = Convert.ToInt32(prt);
            }
            catch
            {
                port = 9000;
            }

            soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soc.Connect(new IPEndPoint(ip, port));
            rec.Start();
            byte[] data = Encoding.Default.GetBytes("<" + name + "> Connected");
            soc.Send(data, 0, data.Length, 0);

            while (soc.Connected)
            {
                byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + Console.ReadLine());
                soc.Send(sdata, 0, sdata.Length, 0);

            }

        }
    }
}




Output:

Server ;




Client :




From this article , I hope you can learn how to create a sample chat application.

10 comments:

  1. I am using this code in windows form after modification according to me now and Creating a new socket but it stops at "acc = soc.Accept();". Why?

    ReplyDelete
    Replies
    1. Soccet is waiting for new request accept from the client when it reads the request , it will move to the next line of code

      Delete
  2. soc.Connect(new IPEndPoint(ip, port)); when i enter the port number it keep prob with this code. why?

    ReplyDelete
    Replies
    1. Hi,
      May be ur port number is not available, or paste the issue that ur facing

      Delete
  3. can u possible using ddns host name..

    ReplyDelete
  4. Thanks a lot for this wonderful article.

    ReplyDelete
  5. i have used same code but it didn't work it on window 7.

    ReplyDelete
  6. An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

    Additional information: No connection could be made because the target machine actively refused it

    ReplyDelete
    Replies
    1. Please do the following steps to resolve this issue:
      In windows 7 Dns.GetHostEntry also returns IPV6 address , you cant connect the IPv6 address with IPv4 socket

      so change the following line in code
      soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

      to

      soc = new Socket(AddressFamily, SocketType.Stream, ProtocolType.Tcp);

      IP address of localhost can simply get by IPAddress.Loopback (127.0.0.1) or IPAddress.IPv6Loopback (::1).

      Even you can try this also,by changing the following host file in system
      Edit C:\Windows\System32\drivers\etc\hosts and add the line "127.0.0.1 localhost" (if its not there, excluding quotes)



      Delete
  7. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Dot Net Training in Chennai. or learn thru ASP.NET Online Training . Nowadays Dot Net has tons of job opportunities on various vertical industry.

    ReplyDelete