How to C# Chat Server
The System.Net classes provide the functionality that is similar to Microsoft WinInet API . Peer-to-peer Microsoft Windows applications that act as servers and clients to send and receive data. The basic function of the C# Chat Server here is to listening the incoming connection request from Clients, and when the Chat Server gets a message , it Broadcast the message to all the Clients currently connected to the C# Chat Server .
In the previous section C# Multi Threaded Socket Program we saw a C# Multithreaded Server Socket Program communicate with more than one Client at the same time . If you don't know the basics of Socket programming , take a look at the section C# Socket Programming before you start this section.
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 listening to the PORT 8888 for the connection request from clients . When the server gets a connection request from client, it add the name of the Client into a clientsList ( Here it is a Hashtable ) and create a new thread for communication with 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 other and they can communicate through Chat Server.
broadcast(dataFromClient, clNo, true);
The client list we implemented here is a HashTable . The clientsList stores the Client Name ( ie the first message from Client ) and an instance of the Client Socket .
When a Chat Client connected to C# Chat 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 Socket and the incoming Client Socket.
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
When Server gets a message from any of the currently 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.
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.
|