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

Réseau .NET Discussion :

Socket Exception connexion abondonné


Sujet :

Réseau .NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre à l'essai
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2012
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Avril 2012
    Messages : 2
    Par défaut Socket Exception connexion abondonné
    bonsoir, je suis en train de développé une application Serveur/Client (messagerie) en c# et j'utilise les sockets asynchrones, la connexion marche très bien ainsi le premier échange (serveur reçoit le message et envoie le premier message), le problème se situe dans le deuxième échange et un socketException apparu indiquant que la connexion est abondonné d'un logiciel de la machine hote au niveau de BeginReceive coté Client.
    Bref je vous montre mon code et j’espère que je trouve une aide pour ce problème:
    coté 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
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
     
     
    public class Server
    {
       public static Socket  main_tcp_Sock;
        private static ManualResetEvent acceptDone = new ManualResetEvent(false);
        private static ManualResetEvent sendDone = new ManualResetEvent(false);
        private static ManualResetEvent recvDone = new ManualResetEvent(false);
        private static ManualResetEvent closeDone = new ManualResetEvent(false);
        //int cl_Count = 0;
        static List<StateObject> connection_List = new List<StateObject>();
        private static String response = String.Empty;
     
     
        public class StateObject
        {
            public Socket current_Socket = null;
            public byte[] data = new byte[256];
            public string id = string.Empty;
        }
     
     
        public static void Server_Start()
        {
     
            //Creating socket
            main_tcp_Sock = new Socket(AddressFamily.InterNetwork,
                                      SocketType.Stream,
                                      ProtocolType.Tcp);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8004);
            //Bind socket
            try
            {
                main_tcp_Sock.Bind(ipLocal);
                Console.WriteLine("Server has started successfully!");
     
     
                //Start listening
                main_tcp_Sock.Listen(100);
                while (true)
                {
     
                    acceptDone.Reset();
                    Console.WriteLine("Waiting for a connection...");
     
                    //AsyncAccept
                    main_tcp_Sock.BeginAccept(new AsyncCallback(On_Connect), main_tcp_Sock);
                    acceptDone.WaitOne();
                    Console.WriteLine("\nPress any button to continue...\n\n");
                    Console.ReadKey(true);
                }
            }
     
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
     
        }
     
        public static void On_Connect(IAsyncResult asyn)
        {
     
            try
            {
     
                Socket listener = (Socket)asyn.AsyncState;
                Socket handler = listener.EndAccept(asyn);
                acceptDone.Set();
     
                StateObject connection = new StateObject();
                connection.current_Socket = handler;
     
                if (!connection_List.Contains(connection))
                {
                    lock (connection_List)
                    {
                        connection_List.Add(connection);
                        connection.id = "00" + connection_List.Count.ToString() + " ";
                    }
                }
     
     
     
     
     
                        recvDone.Reset();
                        Receive(connection.current_Socket);
                        recvDone.WaitOne();
     
                        sendDone.Reset();
     
                        Send(connection.current_Socket, "salut");
     
                        sendDone.WaitOne();
     
     
                    closeDone.Reset();
                    Socket_Close(connection.current_Socket);
                    closeDone.WaitOne();
     
            }
     
            catch (Exception e)
            {
                Console.WriteLine("On_Connect Error: {0}", e.ToString());
                Console.ReadKey(true);
            }
        }
     
        public static void Receive(Socket handler)
        {
            try
            {
                StateObject connection = new StateObject();
                connection.current_Socket = handler;
                connection.current_Socket.BeginReceive(connection.data, 0, connection.data.Length, 0,
                    new AsyncCallback(On_Receive), connection);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
     
        }
        public static void On_Receive(IAsyncResult asyn)
        {
            string content = "";
            string temp = "";
            StateObject connection = (StateObject)asyn.AsyncState;
            Socket handler = connection.current_Socket;
            int size = handler.EndReceive(asyn);
     
     
            Console.WriteLine("ConnID from receive: " + connection.id);
            if (size > 0)
            {
                temp += Encoding.ASCII.GetString(connection.data);
            }
            if (temp.IndexOf("<EOF>") > -1)
            {
     
                content += temp.Substring(0, temp.IndexOf("\0"));
                Console.WriteLine("Read {0} bytes from socket. \nMessage: {1}", content.Length, content);
     
                lock (connection_List)
                {
                    foreach (StateObject conn in connection_List)
                    {
                        if (conn != connection)
                        {
                            content.Insert(0, connection.id);
                            response = content;
                        }
     
                    }
                }
                recvDone.Set();
            }
            else
            {
                handler.BeginReceive(connection.data, 0, connection.data.Length, 0, new AsyncCallback(On_Receive), connection);
            }
     
        }
     
        public static void Send(Socket handler, String message)
        {
            byte[] data = Encoding.ASCII.GetBytes(message);
            handler.BeginSend(data, 0, data.Length, 0, new AsyncCallback(On_Send), handler);
     
        }
     
        public static void On_Send(IAsyncResult result)
        {
            try
            {
                StateObject state = new StateObject();
                Socket handler = (Socket)result.AsyncState;
                state.current_Socket = handler;
                int size = state.current_Socket.EndSend(result);
                if (size > 0)
                {
                    sendDone.Set();
                }
     
                else state.current_Socket.BeginSend(state.data, 0, state.data.Length, SocketFlags.None,
                    new AsyncCallback(On_Send), state);
                Console.WriteLine("Bytes sent to client: {0}", size);
     
                sendDone.Set();
            }
     
            catch (Exception e)
            {
                Console.WriteLine("On_Send e, error: " + e.ToString());
                Console.ReadKey(true);
            }
        }
        public static void Socket_Close(Socket sock)
        {
            sock.LingerState = new LingerOption(true, 50);
     
            sock.Shutdown(SocketShutdown.Both);
            sock.Close();
            closeDone.Set();
        }
     
            public static int Main(String[] args)
            {
                Server.Server_Start();
     
                return 0;
            }
     
    }
    coté 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
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
     
     
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Text;
     
    // State object for receiving data from remote device.
    public class StateObject
    {
        // Client socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 655360;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
    }
     
    public class AsynchronousClient
    {
        public static int count = 0;
     
        // The port number for the remote device.
        private const int port = 8004;
        // ManualResetEvent instances signal completion.
        private static ManualResetEvent connectDone = new ManualResetEvent(false);
        private static ManualResetEvent sendDone = new ManualResetEvent(false);
        private static ManualResetEvent receiveDone = new ManualResetEvent(false);
       private static ManualResetEvent closeDone = new ManualResetEvent(false);
        // The response from the remote device.
        private static String response = String.Empty;
     
        private static void StartClient()
        {
            // Connect to a remote device.
     
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            Start(client, remoteEP);
     
        }
     
     
        public static void Start(Socket client, EndPoint remoteEP)
        {
            try
            {
                while (true)
                {
                    //if (count >= 30)
                    //{
     
                    //    Thread.Sleep(100);
                    //    if (count >= 1000)
                    //    {
                    //        count = 0;
                    //        Thread.Sleep(1500);
                    //    }
                    //}
     
                    Console.WriteLine(count);
                    connectDone.Reset();
                    client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
                    connectDone.WaitOne();
                    // "8=FIX.4.2|9=90|35=A|49=salah|56=djdjhe|34=14|52=12:45|10=100"
                    for (int i = 0; i <= 10; ++i)
                    {
                        string sai;
                        Console.WriteLine("ecrire une clé");
                        sai = Console.ReadLine();
                        Console.WriteLine("vs avez saisie: {0}", sai);
                        if (sai == "o")
                        {
                            // Send test data to the remote device.
                            sendDone.Reset();
     
                            Send(client, "haw text <EOF>\n");
     
                            sendDone.WaitOne();
     
                            // Receive the response from the remote device.
                            receiveDone.Reset();
                            Receive(client);
                            receiveDone.WaitOne();
                            Console.WriteLine("Response received :\n {0}", response);
     
                        }
                        else break;
     
     
                    }   
     
                     // Release the socket.
     
     
     
                    closeDone.Reset();
                    Socket_Close(client);
                    closeDone.WaitOne();
     
     
                    ++count;
                }
     
            }
            catch (ObjectDisposedException)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint remote = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
     
                Start(sock, remote);
     
            }
            catch (SocketException)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork,
                           SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint remote = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
     
                Start(sock, remote);
     
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
        }
     
        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;
     
                // Complete the connection.
                client.EndConnect(ar);
     
                Console.WriteLine("Socket connected to {0}",
                    client.RemoteEndPoint.ToString());
     
                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
        }
     
        private static void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;
     
                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
     
            }
        }
     
        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket 
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
     
                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);
     
                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
     
                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    // All the data has arrived; put it in response.
                    if (state.sb.Length > 1)
                    {
                        response = state.sb.ToString();
                    }
                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
     
            }
        }
     
        private static void Send(Socket client, String data)
        {
            try
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);
     
                // Begin sending the data to the remote device.
                client.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), client);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
        }
     
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;
     
                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to server.", bytesSent);
     
                // Signal that all bytes have been sent.
                sendDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
        }
     
        public static void Socket_Close(Socket sock)
        {
            try
            {
                sock.LingerState = new LingerOption(true, 50);
     
                sock.Shutdown(SocketShutdown.Both);
                sock.Close();
                closeDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadKey(true);
            }
        }
     
        public static int Main(String[] args)
        {
     
            StartClient();
            return 0;
        }
    }
    Je crois que le problème se situe au niveau la clôture du Socket coté Serveur mais j'arrive pas à le résoudre. Merci d'avance.

  2. #2
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2011
    Messages
    269
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 269
    Par défaut
    Bonjour,

    Le probleme est dans ton serveur, dans le handler de connection tu ferme le socket de communication client-serveur.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    public static void On_Connect(IAsyncResult asyn)
    {
        Socket handler = listener.EndAccept(asyn);
        connection.current_Socket = handler;
        // ... //
        Socket_Close(connection.current_Socket);
        // ... //
    }
    Si tu ferme le socket coté, serveur ton client ne peut plus écrire dessus.

    PS :
    On ne traite pas les message dans le handler de connection. On crée un thread qui s’occupera de gérer le(s) socket(s) de communication avec le client(s). Tu dois maintenir ouvert autant de socket que tu as de client connecté.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Exception : connexion refused lors de la création d'un Socket
    Par wilv8 dans le forum API standards et tierces
    Réponses: 13
    Dernier message: 19/07/2010, 10h04
  2. Gestion exception connexion BDD
    Par Aizen64 dans le forum ASP.NET
    Réponses: 3
    Dernier message: 25/02/2008, 21h43
  3. socket pthread connexion
    Par cmoibal dans le forum Réseau
    Réponses: 1
    Dernier message: 23/05/2007, 13h12
  4. Problème Socket Exception
    Par Royd938 dans le forum Langage
    Réponses: 6
    Dernier message: 28/11/2006, 11h18
  5. Réponses: 6
    Dernier message: 25/08/2006, 20h01

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