Client Server programming in C# (Chat application)
So let's develop a Client Server Windows Forms C# application (chat application). First let's create this Windows Form:
TextBoxes names : ServerIPtextBox, ServerPorttextBox, ClientIPtextBox, ClientPorttextBox, ChatScreentextBox, MessagetextBox.
Then add two BackgroundWorker to the project.
And add these namespaces to the project:
using System.Net;
using System.Net.Sockets;
using System.IO;
After that, declare these variables:
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public String TextToSend;
And add this code in Form1():
public Form1()
{
InitializeComponent();
IPAddress[] localIP= Dns.GetHostAddresses(Dns.GetHostName());
foreach(IPAddress address in localIP)
{
if(address.AddressFamily == AddressFamily.InterNetwork)
{
ServerIPtextBox.Text = address.ToString();
}
}
}
In StartButton click event add this code:
private void StartButton_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextBox.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
In ConnectButton click event add this code:
private void ConnectButton_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(ClientIPtextBox.Text), int.Parse(ClientPorttextBox.Text));
try
{
client.Connect(IpEnd);
if(client.Connected)
{
ChatScreentextBox.AppendText("Connected to server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
In backgroundWorker1 DoWork event add this code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(client.Connected)
{
try
{
recieve = STR.ReadLine();
this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
{
ChatScreentextBox.AppendText("You:" + recieve + "\n");
}));
recieve = "";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
And in backgroundWorker2 DoWork event add this code:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if(client.Connected)
{
STW.WriteLine(TextToSend);
this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
{
ChatScreentextBox.AppendText("Me:" + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending failed");
}
backgroundWorker2.CancelAsync();
}
Finally in SendButton click event add this code:
private void SendButton_Click(object sender, EventArgs e)
{
if(MessagetextBox.Text!="")
{
TextToSend = MessagetextBox.Text;
backgroundWorker2.RunWorkerAsync();
}
MessagetextBox.Text = "";
}
Then let's run the application and open a second instance to it from (%project directory%\bin\Debug). Open two instances for testing purposes in your computer, then give the IP address and Port number to the two instances. Then connect both Applications and start sending messages.
Check this video for more explanation:
Client Server programming in C# (Chat application)
Reviewed by Bloggeur DZ
on
08:14
Rating:
Thanks a lot!
RépondreSupprimerThanks a lot! I'm am having problem in stopping the server and also in disconnecting the client. Can you send me the code for both situations. Thanks in advance.
RépondreSupprimerit is giving an error . can u help me with that ASAP
RépondreSupprimerhello,
RépondreSupprimerI have a problem, when i press the "START" button, my application crashes. Anyone have any clue of what's going on ?
Thanks in advance! :-)
thank alot
RépondreSupprimerHow Can I run this client application in one pc and server application in other PC of this example?
RépondreSupprimerCan verify this still works great at start of 2019.
RépondreSupprimerDo note this is done in windows forms and not WPF.
Thanks for the tut and good luck to all.
This works perfectly for what I needed!
RépondreSupprimerIs it for LAN?
RépondreSupprimerThank you for the code. Very succinct. Worked great!
RépondreSupprimerHi, how to write these lines in wpf ? this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
RépondreSupprimer{
ChatScreentextBox.AppendText("Me:" + TextToSend + "\n");
}));
I am getting error on the IP line. It says string is not in correct form.
RépondreSupprimerTcpListener listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextBox.Text));
PLEASE RESPOND: I have an error for every "MessageBox.Show(ex.Message.ToString());" and I don't know why...
RépondreSupprimerit was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. free tango download
RépondreSupprimer