C# socket error 10022

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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(AddressFamily.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);            } 

回答1:

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.



文章来源: C# socket error 10022
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!