Simple Client/Serveur TCP

 01/01/2019 |   Admin |  C#

Tags: Réseau

Voici les bases pour implémenter un client/serveur TCP en c# :

Le client :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
 
public class Client
{
    public static void Main(string[] args)
    {
        try
        {
            string adresseIp = "Votre IP";
            int port = 8001;
 
            TcpClient client = new TcpClient();
            Console.WriteLine("Connexion.....");
            client.Connect(adresseIp, port);
            Console.WriteLine("Connecté");
           
            string chaineAenvoyer = string.Empty;
            while (chaineAenvoyer.ToLower() != "quit")
            {
                Console.WriteLine("\nChaine a envoyer : ");
                chaineAenvoyer = Console.ReadLine();
 
                Stream stream = client.GetStream();
                ASCIIEncoding encoding = new ASCIIEncoding();
 
                byte[] byteAenvoyer = encoding.GetBytes(chaineAenvoyer);
                Console.WriteLine("Transmission.....");
                stream.Write(byteAenvoyer, 0, byteAenvoyer.Length);
                byte[] byteEnvoyes = new byte[100];
                int nbBytes = stream.Read(byteEnvoyes, 0, 100);
                for (int i = 0; i < nbBytes; i++)
                {
                    Console.Write(Convert.ToChar(byteEnvoyes[i]));
                }
            }
 
            client.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Erreur : " + e.StackTrace);
        }
    }
}

Le serveur :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
 
public class Server
{
    public static void Main(string[] args)
    {
        try
        {
            string adresseIp = "Votre IP";
            int port = 8001;
 
            IPAddress ipAd = IPAddress.Parse(adresseIp);
            TcpListener listener = new TcpListener(ipAd, port);
 
            listener.Start();
            Console.WriteLine("Le serveur écoute sur le port " + port + " ...");
            Console.WriteLine("Le point de terminaison local est :" + listener.LocalEndpoint);
            Console.WriteLine("Attente d'une connexion.....");
 
            Socket socket = listener.AcceptSocket();
            Console.WriteLine("Connexion acceptee de " + socket.RemoteEndPoint);
 
            string motRecu = string.Empty;
 
            while (motRecu.ToLower() != "quit")
            {
                motRecu = string.Empty;
                Console.WriteLine("Reception...");
 
                byte[] byteRecu = new byte[100];
                int nbBytes = socket.Receive(byteRecu);
                for (int i = 0; i < nbBytes; i++)
                {
                    motRecu += Convert.ToChar(byteRecu[i]);
                }
                Console.Write(motRecu);
 
                if (motRecu == "alien")
                {
                    Console.WriteLine("");
                    Console.WriteLine(@"      _       _");
                    Console.WriteLine(@"     (_\     /_)");
                    Console.WriteLine(@"       ))   ((");
                    Console.WriteLine(@"     .-'''''''-.  ");
                    Console.WriteLine(@" /^\/  _.   _.  \/^\");
                    Console.WriteLine(@" \(   /__\ /__\   )/");
                    Console.WriteLine(@"  \,  \o_/_\o_/  ,/");
                    Console.WriteLine(@"    \    (_)    /");
                    Console.WriteLine(@"     `-.'==='.-'");
                    Console.WriteLine(@"      __) - (__  ");
                    Console.WriteLine(@"     /  `~~~`  \");
                    Console.WriteLine(@"    /  /     \  \");
                    Console.WriteLine(@"    \ :       ; /");
                    Console.WriteLine(@"     \|==(*)==|/");
                    Console.WriteLine(@"      :       :");
                    Console.WriteLine(@"       \  |  /");
                    Console.WriteLine(@"     ___)=|=(___");
                    Console.WriteLine(@"    {____/ \____}");
                }
                ASCIIEncoding encoding = new ASCIIEncoding();
                socket.Send(encoding.GetBytes("La chaine a ete recue par le serveur."));
                Console.WriteLine("\nEnvoi de l'acknowledgement");
 
            }
            socket.Close();
 
           listener.Stop();
        }
        catch (Exception e)
        {
            Console.WriteLine("Erreur : " + e.StackTrace);
        }
    }
}

 

Pour tester il suffit de lancer le serveur dans un premier temps puis le client.

Les messages seront saisis dans le client puis affichés dans le serveur.

Pour quitter l'application il suffit d'entrer la commande "quit".

Pour afficher un petit dessin il faut taper la commande "alien" ! (pour le fun)

Ceci est la base d'un client serveur TCP. A partir de cette base on peut imaginer de nombreuses implémentations.