C# .NET Socket connection issue - Only one usage of each socket address is normally permitted

.net, c#, compact-framework, windows-mobile

Solution

Yes, your server socket is likely in the TIME_WAIT state.

You can access the underlying ServerSocket and then use SetSocketOption and specify ReuseAddress.

Problem

I am having the following issue: Once I close my WM6 application and then try to start it again i get this error: Only one usage of each socket address (protocol/network address/port) is normally permitted at System.Net.Sockets.Socket.Bind(EndPoint localEP) at System.Net.Sockets.Socket.TcpListener.Start() ... I think this is due to the time interval for the connection to timeout, so I would like to close all open conections and force it to create a new connection, is this the correct way to proceed or is there a different way to handle this? Here is the code used to start listening: ``` /// <summary> /// Listens Asynchronously to Clients, creates a recieveMessageHandler to process the read. /// /// Check WIKI, TODOS /// </summary> /// <returns></returns> public void Listen() { myTcpListener.Start(); while (true) { //blocks until a client has connected to the server try { TcpClient myTcpClient = myTcpListener.AcceptTcpClient(); DateTime now = DateTime.Now; //Test if it's necessary to create a client ClientConnection client = new ClientConnection(myTcpClient, new byte[myTcpClient.ReceiveBufferSize]); // Capture the specific client and pass it to the receive handler client.NetworkStream.BeginRead(client.Data, 0, myTcpClient.ReceiveBufferSize, r => receiveMessageHandler(r, client), null); } catch (Exception excp) { Debug.WriteLine(excp.ToString()); } } } ```

Original source