Chat continu

Voici l’implémentation d’un chat bidirectionnel utilisant le multithreading pour éviter les blocages de l’interface.

La version WinForm utilise BackgroundWorker pour réaliser la boucle de réception sur un thread séparé, tandis que l’envoi des messages se déclenche depuis le thread UI. Cela contourne cette limitation et permet un échange bidirectionnel fluide.

Voici d’abord le code côté serveur

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Service
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        IPAddress ip;
        TcpListener listener;
        TcpClient tcpClient;

        private void buttonStart_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            ip = IPAddress.Parse(this.textBoxIP.Text);
            listener = new TcpListener(ip, Convert.ToInt32(this.textBoxPort.Text));
            listener.Start();
            this.textBoxInfo.Text = "Serveur démarré - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            tcpClient = listener.AcceptTcpClient();
            this.textBoxInfo.Text = "Connexion établie - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = new byte[1024];
            while (true)
            {
                int length = stream.Read(byteArray, 0, 1024);
                string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
                this.textBoxInfo.Text = "Reçu : " + receiveMessage + " - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "Envoyé \"" + message + "\" - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray, 0, byteArray.Length);
        }
    }
}
Langage du code : C# (cs)

Ensuite le code côté client

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        TcpClient tcpClient;
        private void buttonStart_Click(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();
            try
            {
                tcpClient.Connect(this.textBoxIP.Text, Convert.ToInt32(this.textBoxPort.Text));
                this.textBoxInfo.Text = "Connexion établie - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
                this.backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Échec de connexion - "+ex.Message);
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "Envoyé \""+message+"\" - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray, 0, byteArray.Length);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = new byte[1024];
            while (true)
            {
                int length = stream.Read(byteArray, 0, 1024);
                string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
                this.textBoxInfo.Text = "Reçu : " + receiveMessage + " - " + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            }
        }
    }
}
Langage du code : C# (cs)

Chat continu

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *