开发者

C# socket error 10022

I have an error 10022 in an application using sockets in C# .NET3.5.

In my code, I bind the socket to the local IP adress. When I don"t need it anymore, I just Disconnect it ( reader.socket.Disconnect(true); ) with "true" to be able to re-use it.

But when I call the "bind" method again, it crashes with the 10022 error (invalid argument).

If I set the line with this method as a comment, it then crashes on the line "listen", saying that a connection is already set (although I called disconnect !)

Any idea?

Thanks


Here is the part of code which fail :

public void WaitConnexion(IPEndPoint localEP)
        {
            if (localEP.Port != 9000)
            {
                MessageBox.Show("Le port doit être 9000");
                return;
            }
            LocalEndPoint = localEP;

            if (reader.socket.Connected)
            {
                MessageBox.Show("Vous êtes déjà connecté", "Conflit de connexion", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            // on bind le socket avec le endpoint local, et on le met en attente de connexion asynchrone

          //  reader.socket = new Socket(A开发者_运维技巧ddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            reader.socket.Bind(localEP);

            reader.socket.Listen(1);

            reader.socket.BeginAccept(new AsyncCallback(WaitConnexionCallBack), reader.socket);
        }

and here is the diconnect method with its callback :

 public void Disconnect()
        {
            if (!reader.socket.Connected)
                return;


            reader.socket.BeginDisconnect(true, new AsyncCallback(DisconnectCallBack), reader.socket);


        }

       private void DisconnectCallBack(IAsyncResult result)
        {
            reader.socket = (result.AsyncState as Socket);
            reader.socket.EndDisconnect(result);


            if (Disconnected != null)
                Disconnected(this, EventArgs.Empty);



        }


I found the solution.

It seems that the garbage collector wasn't called fast enough, letting in memory some socket's value which where actually disposed.

Code Modification in DisconnectedCallBack :

   reader.socket = (result.AsyncState as Socket);
   reader.socket.EndDisconnect(result);
   reader.socket.close(0);
   GC.Collect();  // call garbage collector to clean the socket

Code modification in WaitConnexion :

 reader.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Re-creating the socket.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜