IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Envoie d'un objet sérialisé via un TCPClient


Sujet :

C#

  1. #1
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut Envoie d'un objet sérialisé via un TCPClient
    Bonjour, j'ai un problème lors de l'envoie d'un objet sérialisé à un serveur. J'ai essayé de chercher sur le net j'ai pas pu identifié la source de mon erreur. En fait, j'ai un objet "IdentificationClient" que je voudrais l'envoyer à un serveur.
    Voilà le code que j'ai fait pour la partie client :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    fluxClient = client.GetStream();// client de type TCPClient
                if (fluxClient.CanWrite)
                {
                    MemoryStream ms = new MemoryStream();
                    IFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, IdentificationClient);//Objet à sérialiser
                    byte[] writerbuffer = ms.GetBuffer();
                    ms.Close();
                    fluxClient.Write(writerbuffer, 0, writerbuffer.Length);
                    fluxClient.Close();
                  }
    Dans la partie serveur je souhaite récupérer l'objet pour effectuer des traitements :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
    NetworkStream fluxClient = serviceClient.GetStream();
                if (fluxClient.CanRead)
                {
                    byte[] data = new byte[serviceClient.ReceiveBufferSize];
                    MemoryStream ms2 = new MemoryStream(data);
                    fluxClient.Read(data, 0, (int)serviceClient.ReceiveBufferSize);
                    IFormatter formatter = new BinaryFormatter();
                    IdentificationClient p = (IdentificationClient)formatter.Deserialize(ms2); // you have to cast the deserialized object
                    fluxClient.Close();
                    //client.Close();
                    //server.Stop(); 
                    String loginUser = p.LoginClient;//renvoie le login
                    MessageBox.Show(loginUser);
                }
    J'espère que vous pouvez m'aider.

  2. #2
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Salut,

    Qu'est-ce qui ne marche pas? Y a-t-il un message d'erreur?
    Tu l'envois sur quel port?
    Peux-tu nous montrer coment tu instancies le client?

    Il y a un bon exemple ici: http://msdn.microsoft.com/en-us/libr...nt(VS.80).aspx

    A+

  3. #3
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut
    Bonjour,

    En fait, je voulais envoyer un objet et pas une chaine de caractère. J'ai vu sur internet qu'il faut passer par la sérialization binaire pour pouvoir envoyer plusieurs types via les sockets. Donc, mon problème c'est au niveau de l'envoie de l'objet sérializé.

    J'ai une autre question : est ce que je pourrai créer plusieurs objets de types NetworkStream ou bien le même objet sert à lire et à écrire ?

  4. #4
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Citation Envoyé par Immobilis Voir le message
    Qu'est-ce qui ne marche pas? Y a-t-il un message d'erreur?
    Tu l'envois sur quel port?
    Peux-tu nous montrer coment tu instancies le client?

  5. #5
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut
    J'ai pas de messages d'erreur, mais je reçois rien voilà. La connexion entre le client serveur marche bien, j'ai déjà essayé d'envoyer des chaines de caractères.

  6. #6
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Quel port? Si c'etait sur un serveur web cela simplifierait les choses.

    Y'a quoi derrière qui écoute?

    Et ce tuto? http://defaut.developpez.com/tutorie...t/remoting/cs/

  7. #7
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut
    J'utilise le port 7000. C'est juste j'ai besoin de développer une application Client/Serveur

  8. #8
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Citation Envoyé par Immobilis Voir le message
    Y'a quoi derrière qui écoute?
    Et le tuto?

  9. #9
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut
    Mais je vois que le tuto montre la sérialization !!! Il explique l'envoie d'une chaine

  10. #10
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Ben une chaine c'est un type valeur, mais ce pourrait-être n'importe quoi:
    Le marshalling, c'est un peu comme lorsque que vous mettez un objet dans un colis, vous le placez en un format qui permettra son transport. Le réseau étant ici la Poste ou un transporteur quelconque. Le fait de mettre l'objet dans le paquet, c'est du marshalling, le fait de déballer le paquet et d'en extraire l'objet est le unmarshalling.
    De même, plus l'objet est gros et lourd, plus le timbre coûtera cher. Il en est de même avec un réseau où le coût en bande passante augmentera en même temps que le poids des données.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    try
    {
    	TcpChannel channel = new TcpChannel();
    	ChannelServices.RegisterChannel(channel);
    	remoteOperation = (RemotingInterfaces.IRemoteOperation)Activator.GetObject(
    		typeof (RemotingInterfaces.IRemoteOperation),
    		"tcp://localhost:1069/RemoteOperation");
    }
    catch{ MessageBox.Show("Erreur de connexion au serveur"); }
    Dans ce code le type n'est pas précisé.

  11. #11
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut
    Merci pour votre aide, mais je vois que vous utilisez le Remoting ce qui change totalement mon contexte. Pour quoi on utilise pas la séralisation/désérialisation ?

  12. #12
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    J'utilise la dénomination sérialisation pour définir le processus selon lequel un objet (une classe de transfert de données) est transformé en un "flux" xml pour être envoyé sur le réseau.
    J'utilise la dénomination désérialisation pour définir le processus selon lequel un "flux" xml envoyé sur le réseau est transformé en un objet (une classe de transfert de données).
    En général j'utilise ces processus pour permettre d'établir une communication client (Client Web)/serveur (IIS). Pour tout autre port, il semble que le Marshalling soit de rigueur.

    A+

  13. #13
    Membre habitué
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    236
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Février 2007
    Messages : 236
    Points : 194
    Points
    194
    Par défaut
    Merci pour votre aide, mais on peut sérialiser un objet en biniare !

  14. #14
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Le transport à travers le réseau est binaire

    Un client Ftp par exemple a une propriété Binaire pour l'indiquer explicitement.

  15. #15
    Expert éminent
    Avatar de Immobilis
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2004
    Messages
    6 559
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 559
    Points : 9 506
    Points
    9 506
    Par défaut
    Salut,

    J'ai suivit le tuto de la msdn posté plus haut et j'ai pu envoyer du client au serveur une classe sérialisée au format Xml.
    La classe DTO
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    using System;
    using System.Collections.Generic;
    using System.Text;
     
    namespace ConsoleApplication1
    {
        [Serializable]
        public class HelloWorld
        {
            private double _height;
     
            public double Height
            {
                get { return _height; }
                set { _height = value; }
            }
            private string _name;
     
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
            private DateTime _birth;
     
            public DateTime Birth
            {
                get { return _birth; }
                set { _birth = value; }
            }
     
            public override string ToString()
            {
                return string.Format("Name {0}, Birth {1}, Height {2}.", this.Name, this.Birth.ToShortDateString(), this.Height);
            }
        }
    }
    Le serveur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Sockets;
    using System.Net;
    using System.Xml.Serialization;
    using ConsoleApplication1;
    using System.IO;
    using System.Xml;
     
    namespace TcpListner
    {
        class MyTcpListner
        {
            static void Main(string[] args)
            {
                TcpListener server = null;
                try
                {
                    // Set the TcpListener on port 13000.
                    Int32 port = 13000;
                    IPAddress localAddr = IPAddress.Parse("127.0.0.1");
     
                    // TcpListener server = new TcpListener(port);
                    server = new TcpListener(localAddr, port);
     
                    // Start listening for client requests.
                    server.Start();
     
                    // Buffer for reading data
                    Byte[] bytes = new Byte[256];
                    String data = null;
     
                    // Enter the listening loop.
                    while (true)
                    {
                        Console.Write("Waiting for a connection... ");
     
                        // Perform a blocking call to accept requests.
                        // You could also user server.AcceptSocket() here.
                        TcpClient client = server.AcceptTcpClient();
                        Console.WriteLine("Connected!");
     
                        data = null;
     
                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            int i;
     
                            // Loop to receive all the data sent by the client.
                            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
     
                                // Translate data bytes to a ASCII string.
                                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                                Console.WriteLine("Received: {0}", data);
     
                                HelloWorld hello = null;
                                XmlSerializer serializer = new XmlSerializer(typeof(HelloWorld));
                                XmlReader xr = XmlReader.Create(new StringReader(data));
                                if (serializer.CanDeserialize(xr))
                                    hello = (HelloWorld)serializer.Deserialize(xr);
     
     
                                // Process the data sent by the client.
                                data = string.Format("Hello {0} you are born on {1}. You are {2}m tall.",
                                    hello.Name, hello.Birth.ToShortDateString(), hello.Height);
     
                                byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
     
                                // Send back a response.
                                stream.Write(msg, 0, msg.Length);
                                Console.WriteLine("Sent: {0}", data);
                            }
                        }
                        // Shutdown and end connection
                        client.Close();
                    }
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }
                finally
                {
                    // Stop listening for new clients.
                    server.Stop();
                }
                Console.WriteLine("\nHit enter to continue...");
                Console.Read();
            }
        }
    }
    Le client
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    using System;
    using System.IO;
    using System.Text;
    using System.Globalization;
    using System.Net.Mail;
    using System.Configuration;
    using System.Net;
    using System.Net.Sockets;
    using System.Xml.Serialization;
     
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                HelloWorld hello = new HelloWorld();
                hello.Birth = new DateTime(1972, 8, 27);
                hello.Name = "Immobilis";
                hello.Height = 1.72;
     
                Connect("127.0.0.1", hello);
                Console.ReadLine();
            }
     
            static void Connect(String server, HelloWorld hello)
            {
                try
                {
                    // Create a TcpClient.
                    // Note, for this client to work you need to have a TcpServer 
                    // connected to the same address as specified by the server, port
                    // combination.
                    Int32 port = 13000;
                    TcpClient client = new TcpClient(server, port);
     
                    // Translate the passed message into ASCII and store it as a Byte array.
                    XmlSerializer serializer = new XmlSerializer(typeof(HelloWorld));
                    MemoryStream mems = new System.IO.MemoryStream();
                    serializer.Serialize(mems, hello);
     
                    string _str = Encoding.UTF8.GetString(mems.ToArray());
     
                    Byte[] data = System.Text.Encoding.ASCII.GetBytes(_str);
     
                    // Get a client stream for reading and writing.
                    //  Stream stream = client.GetStream();
     
                    using (NetworkStream stream = client.GetStream())
                    {
                        // Send the message to the connected TcpServer. 
                        stream.Write(data, 0, data.Length);
     
                        Console.WriteLine("Sent: {0}", hello.ToString());
     
                        // Receive the TcpServer.response.
     
                        // Buffer to store the response bytes.
                        data = new Byte[256];
     
                        // String to store the response ASCII representation.
                        String responseData = String.Empty;
     
                        // Read the first batch of the TcpServer response bytes.
                        Int32 bytes = stream.Read(data, 0, data.Length);
                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                        Console.WriteLine("Received: {0}", responseData);
                    }
                    // Close everything.
                    client.Close();
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("ArgumentNullException: {0}", e);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }
     
                Console.WriteLine("\n Press Enter to continue...");
                Console.Read();
            }
        }
    }
    Le resultat est dans la miniature, la fenetre au premier plan est celle du serveur.
    Images attachées Images attachées  

Discussions similaires

  1. [AC-2003] Envoi de plusieurs objets via une seule macro
    Par Skoat dans le forum Access
    Réponses: 9
    Dernier message: 03/11/2009, 16h42
  2. Envoie d'objet complexe via HTTPService
    Par rades2006 dans le forum Flex
    Réponses: 9
    Dernier message: 07/10/2009, 13h48
  3. Ajouter objet dynamiquement via un bouton
    Par maxjaco dans le forum SWT/JFace
    Réponses: 3
    Dernier message: 23/06/2006, 16h39
  4. [Sécurité] Problème de récupération d'objet sérialisé
    Par Mysticlolly dans le forum Langage
    Réponses: 6
    Dernier message: 31/03/2006, 14h16
  5. Script d'envoie d'un fichier excel via un formulaire
    Par Morphine.Nw dans le forum ASP
    Réponses: 4
    Dernier message: 26/01/2006, 13h08

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo