Hi
I need help please I wrote this chat application in c#, .net, the chat work beautiful for one client how to make the server accept multiple client at the same time. I nedd your help please.
Here is my simple code,
namespace Server_chat
{
public partial class Form1 : Form
{
TcpListener lyssnare;
TcpClient klient = new TcpClient();
List<TcpClient> klientList = new List<TcpClient>();
//int port = 126;
public Form1()
{
InitializeComponent();
try
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
lyssnare = new TcpListener(endpoint);
lyssnare.Start();
StartaReciving()
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
}
public async void StartaReciving()
{
try
{
while (true)
{
klient = await lyssnare.AcceptTcpClientAsync();
StartReading(klient);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
}
public async void StartReading(TcpClient k)
{
byte[] buffert = new byte[1024];
int n = 0;
try
{
n = await k.GetStream().ReadAsync(buffert, 0, buffert.Length);
}
catch (Exception error)
{
MessageBox.Show(error.Message, Text);
return;
}
richTextBox1.AppendText(Encoding.Unicode.GetString(buffert, 0, n));
StartaLäsning(k);
Console.WriteLine();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Client.cs
TcpClient klient = new TcpClient();
int port = 125;
public Form1()
{
InitializeComponent();
klient.NoDelay = true;
}
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (!klient.Connected)
Startconnection();
}
public async void Startconnection()
{
try
{
IPAddress adress = IPAddress.Parse(textBox1.Text);
await klient.ConnectAsync(adress, port);
}
catch (Exception e)
{
MessageBox.Show(e.Message, Text);
return;
}
button2.Enabled = true;
button1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
Startsending(richTextBox2.Text);
}
public async void Startsending(String message)
{
richTextBox2.Text = textBox1.Text + ":" + port + "> " + richTextBox1.Text;
byte[] ut = Encoding.Unicode.GetBytes(richTextBox2.Text);
try
{
await klient.GetStream().WriteAsync(ut, 0, ut.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Text);
return;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
Thank you!