How To C Chat Server

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

How to C# Chat server programming

Network programming in windows is possible with Sockets .The


Microsoft .NET framework provides two namespaces, System.Net and
System.Net.Sockets for managed implementation of Internet protocols
that applications can use to send or receive data over the Internet .

In the previous section C# Multi Threaded Socket Program we can see a


C# Multi Threaded Server Socket Program communicate with more than
one Client at the same time . But there the communication is occurred
between Server to Client or Client to Server , there is no communication
between Client to Client . C# Chat Server describes how to a Client can
communicate with any number of Clients , currently connected to the Chat
Server .

The main idea behind the C# Chat Server is that each Client send
messages to the Server and the Server broadcast the message to all
Clients currently connected to the Chat Server . From the following picture
you can see how a C# TCP Chat Server is handling communication
between Client to Client .
C# chat server example
The C# Chat Server program has two sections.

1. C# Chat Server

2. C# Chat Client

How to run Chat Server program ?

Create the C# Chat Server and C# Chat Client are two separate C#
projects and compile and build the program. Open a DOS prompt and run
the Server Program first and then run the Client program .

In the Client program, Enter a Chat name and click " Connect to Server
" button . Then you can see the message in the Server program User "
Joined Chat Room " . Similarly you can connect more than one Clients at
the same time and start chatting each other. If you plan to run more than
one client, it is better to copy the .exe file in separate folders and run
from the .exe file.

Next : How to C# Chat Server


How to C# Chat Server
The basic function of the Chat Server here is to listen to the incoming
request from Clients, and when the Server got a message , it Broadcast
the message to all the Clients currently connected to the Chat Server .

In the previous section C# Multi Threaded Socket Program we saw a


Multithreaded Server Socket Program communicate with more than one
Clients at the same time .

The C# Chat Server Program has two sections.

1. Chat Server

2. C# Chat Client

Chat Server

The Chat Server here is a C# Console Based Application and is listen to


the PORT 8888 for the connection request from clients . When the server
got a connection request, it add the name of the Client into a clientsList (
Here it is a Hashtable ) and create a new thread for communicate with the
Server .

clientsList.Add(dataFromClient, clientSocket);

When the Server gets a message from any client , it select all the Clients
from the clientsList and send the message ( Broadcast ) to all Clients
( ie we can say Broadcast ) in the clientsList . So all Client can see the
message of each others and they can communicate through Server.

broadcast(dataFromClient, clNo, true);

The client list we implemented as a HashTable . The clientsList stores the


Client Name ( ie here the first message from Client ) and create an
instance of the Client Socket .
When a Client connected to Server , the Server create a new Thread for
communication . Here we implement a Class handleClient for handling
Client as a separate Thread . The Class handleClient has a function
doChat() is handling the communication between the Server side Client.

handleClinet client = new handleClinet();

client.startClient(clientSocket, dataFromClient, clientsList);

When Server gets a message from any of the connected Chat Client , the
Server Broadcast the message to all Clients. Here we implement a
function broadcast for sending messages to all Clients .

Create a new C# Console Based Application and put the following


source code into the Project.

Next : How to C# Chat Client

Download Source Code


Print Source Code

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

namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();

static void Main(string[] args)


{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;

serverSocket.Start();
Console.WriteLine ("Chat Server Started ....");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();

byte[] bytesFrom = new byte[10025];


string dataFromClient = null;

NetworkStream networkStream = clientSocket.GetStream();


networkStream.Read(bytesFrom, 0,
(int)clientSocket.ReceiveBufferSize);
dataFromClient =
System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0,
dataFromClient.IndexOf("$"));

clientsList.Add(dataFromClient, clientSocket);

broadcast(dataFromClient + " Joined ", dataFromClient,


false);

Console.WriteLine(dataFromClient + " Joined chat room ");


handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient,
clientsList);
}

clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}

public static void broadcast(string msg, string uName, bool flag)


{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream =
broadcastSocket.GetStream();
Byte[] broadcastBytes = null;

if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says
: " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}

broadcastStream.Write(broadcastBytes, 0,
broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class

public class handleClinet


{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;

public void startClient(TcpClient inClientSocket, string clineNo,


Hashtable cList)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}

private void doChat()


{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;

while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0,
(int)clientSocket.ReceiveBufferSize);
dataFromClient =
System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0,
dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " +
dataFromClient);
rCount = Convert.ToString(requestCount);

Program.broadcast (dataFromClient, clNo, true);


}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
} //end class handleClinet
}//end namespace

The C# Chat Server Program has two sections.


1. Chat Server

2. C# Chat Client

How to run Chat Server program ?

Create the C# Chat Server and C# Chat Client are two separate C# projects and compile and
build the program. Open a DOS prompt and run the Server Program first and then run the
Client program .

In the Client program, Enter a Chat name and click " Connect to Server " button . Then you
can see the message in the Server program User "Joined Chat Room" . Similarly you can
connect more than one Clients at the same time and start chatting each other. If you plan to
run more than one client, it is better to copy the .exe file in separate folders and run from
the .exe file.

C# Multi threaded socket programming


C# Multithreaded Socket Programming describes that a Multithreaded
Socket Server can communicate with more than one client at the same
time in the same network. The Microsoft .NET framework provides two
namespaces, System.Net and System.Net.Sockets for managed
implementation of Internet protocols that applications can use to send or
receive data over the Internet .

In the previous chapter C# Socket Programming describes a Server


Socket Program can communicate with only one client at a time . That
means, the C# Server Socket Program does not accept more than one C#
Client Socket Program connection . From the following picture you can
understand how to a C# Multithreaded Server can communicate with
more than one C# Client at the same time .You can see the basics of
Socket Programming in the previous section , before you start this section
take a look at C# Socket Programming .
The basic idea behind Multithreaded Socket Programming is,
whenever the Server gets a connection request from Client side, the
Server create a separate Client Thread in Server side for communicate
with that particular Client Socket. That means, for each Client Socket
there is a separate Client Thread in Server side for independent
communication. So the Client can communicate independently with their
own Client Thread in the Server side.
In the following sections you can see in details of How to a C#
Multithreaded Socket Programming can communicate with more than one
client at the same time.

The C# Multithreaded Socket Programming has two sections.

1. C# Multi Threaded Server Socket Program

2. C# Multi Threaded Client Socket Program

How to run this program ?

Create C# Multi Threaded Server Socket Program and C# Multi Threaded


Client Socket Program in two separate C# projects .

After compile and build the projects, open a DOS prompt and run the
Server Program first. Then you will get the message "Server started" in
Server side.

Next you start the Client program , then you can see the message from
Server . You can start more than one client at the same time and
communicate with the Server program. If you plan to run more than one
client, it is better to run the client program's .exe file to copy in separate
folders and run from .exe file.

Next : C# Multi threaded Server Socket programming

C# Multi threaded Server Socket


programming
MultiThreaded Server Socket Program here is a C# Console based
application , that can handle multiple clients at the same time. Network
programming in windows is possible with sockets , peer-to-peer Microsoft
Windows applications that act as servers and clients to send and receive
data. You can see the basics of C# Socket Programming in the previous
section , before you start this section take a look at C# Socket
Programming .

The C# Multi Threaded Socket Program has two sections.

1. C# Multithreaded Server Socket Program

2. C# Multi Threaded Client Socket Program

Multithreaded Server Socket Program


Here we create a C# Server Socket from TcpListener Class and listen to
PORT 8888 . When the C# Server Socket gets a request from Client side ,
the Server passes the instance of the client request to a separate class
handleClient .For each call from Server Socket , the handleClient class
create new instances for independent communication with the client. In
handleClient class there is a Thread for handling the communication
between the instance of C# Server side client and C# Client from outside .

For each Client request , there is a new thread instant is created in C#


Server for separate communication with Client, so we can connect more
than one client at the same time to the C# Server and communicate
independently to Server .

Create a new C# Console Application project and put the following


source code in the C# project.

Next : C# Multi threaded Client Socket programming

Download Source Code


Print Source Code

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;

serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");

counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" +
Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket,
Convert.ToString(counter));
}

clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}

//Class to handle each client request separatly


public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;

while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0,
(int)clientSocket.ReceiveBufferSize);
dataFromClient =
System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0,
dataFromClient.IndexOf("$"));
Console.WriteLine(" >> " + "From client-" + clNo +
dataFromClient);

rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " +
rCount;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
}
}
}
}
}

The C# Multi Threaded Socket Program has two sections.


1. C# Multithreaded Server Socket Program
2. C# Multi Threaded Client Socket Program

How to run this program ?

Create C# Multithreaded Server Socket Program and C# Multi Threaded Client Socket
Program in two separate C# projects .

After compile and build the projects, open a DOS prompt and run the Server Program
first.Then you will get the message "Server started" in Server side.

Next you start the Client program , then you can see the message from Server . You can start
more than one client at the same time and communicate with the Server program. If you plan
to run more than one client, it is better to run the client program's .exe file to copy in separate
folders and run from .exe file.

C# Multi threaded Client Socket


programming
C# Multithreaded Client Socket Program here is a C# Windows based
application and it can connect to the Server and send the message to the
Server. The C# Server is multithreaded so we can connect more than one
Client program to the Server .

The System.Net classes provide functionality that is similar to Microsoft


WinInet API , it allows classes to communicate with other applications
by using the Hypertext Transfer Protocol (HTTP), Transmission Control
Protocol (TCP), User Datagram Protocol (UDP), and Socket Internet
protocols. You can see the basics of C# Socket Programming in the
previous section , before you start this section take a look at C# Socket
Programming section.
The C# Multi Threaded Socket Program has two sections.

1. C# Multi Threaded Server Socket Program

2. C# Multithreaded Client Socket Program

Multithreaded Client Socket Program

C# MultiThreaded Client Socket Program is a windows based application .


Here the client program is connected to Server's PORT 8888 , and IP
Address here we give Server Address as " 127.0.0.1 " , because Server
and Client program run on the same machine.

clientSocket.Connect("127.0.0.1", 8888);
When the Client gets connected to the C# Server , the Server makes a
separate thread for Client's communication . So we can connect more than
one client and communicate at the same time.

Create a new C# Windows based application and put the following source
code in the Project.

Next : How to C# Chat server programming

Download Source Code


Print Source Code

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new
System.Net.Sockets.TcpClient();
NetworkStream serverStream;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
}

private void button1_Click(object sender, EventArgs e)


{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message
from Client$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

byte[] inStream = new byte[10025];


serverStream.Read(inStream, 0,
(int)clientSocket.ReceiveBufferSize);
string returndata =
System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}

public void msg(string mesg)


{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " +
mesg;
}
}
}

How to run this program ?


The C# Multi Threaded Socket Program has two sections.

1. C# Multi Threaded Server Socket Program

2. C# Multithreaded Client Socket Program

Create C# Multi Threaded Server Socket Program and C# Multithreaded Client Socket
Program in two separate C# projects .

After compile and build the projects, open a DOS prompt and run the Server Program
first.Then you will get the message "Server started" in Server side.

Next you start the Client program , then you can see the message from Server . You can start
more than one client at the same time and communicate with the Server program. If you plan
to run more than one client, it is better to run the client program's .exe file to copy in separate
folders and run from .exe file.

How to C# Chat server programming


Network programming in windows is possible with Sockets .The
Microsoft .NET framework provides two namespaces, System.Net and
System.Net.Sockets for managed implementation of Internet protocols
that applications can use to send or receive data over the Internet .

In the previous section C# Multi Threaded Socket Program we can see a


C# Multi Threaded Server Socket Program communicate with more than
one Client at the same time . But there the communication is occurred
between Server to Client or Client to Server , there is no communication
between Client to Client . C# Chat Server describes how to a Client can
communicate with any number of Clients , currently connected to the Chat
Server .
The main idea behind the C# Chat Server is that each Client send
messages to the Server and the Server broadcast the message to all
Clients currently connected to the Chat Server . From the following picture
you can see how a C# TCP Chat Server is handling communication
between Client to Client .

C# chat server example


The C# Chat Server program has two sections.

1. C# Chat Server

2. C# Chat Client

How to run Chat Server program ?


Create the C# Chat Server and C# Chat Client are two separate C#
projects and compile and build the program. Open a DOS prompt and run
the Server Program first and then run the Client program .

In the Client program, Enter a Chat name and click " Connect to Server
" button . Then you can see the message in the Server program User "
Joined Chat Room " . Similarly you can connect more than one Clients at
the same time and start chatting each other. If you plan to run more than
one client, it is better to copy the .exe file in separate folders and run
from the .exe file.

Next : How to C# Chat Server

How to send email from C#


The Microsoft .NET framework provides two namespaces, System.Net
and System.Net.Sockets for managed implementation of Internet
protocols that applications can use to send or receive data over the
Internet . SMTP protocol is using for sending email from C#. SMTP
stands for Simple Mail Transfer Protocol . C# using System.Net.Mail
namespace for sending email . We can instantiate SmtpClient class and
assign the Host and Port . The default port using SMTP is 25 , but it may
vary different Mail Servers .

The following C# source code shows how to send an email from a Gmail
address using SMTP server. The Gmail SMTP server name is
smtp.gmail.com and the port using send mail is 587 and also using
NetworkCredential for password based authentication.

SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");


SmtpServer.Port = 587;
SmtpServer.Credentials =

new System.Net.NetworkCredential("username", "password");

Next : How to send email with attachment from C#

Download Source Code


Print Source Code

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

mail.From = new
MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";

SmtpServer.Port = 587;
SmtpServer.Credentials = new
System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

You have to provide the necessary information like your gmail username and password etc.

You might also like