Error connecting to C # .NET. - Only one use of each socket address is allowed.

I have the following problem:

As soon as I close my WM6 application and then try to start it again, I get this error: In System.Net.Sockets.Socket.Bind (EndPoint localEP) usually only one use of each socket address is allowed (protocol / network address / port) in System.Net.Sockets.Socket.TcpListener.Start () ...

I think this is due to the time interval for connecting to a timeout, so I would like to close all open connections and make it create a new connection, is this the right way to continue or is there another 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 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());
        }
    }
}
+5
2
+4

, ClientConnection - DLL, , CF.

, MethodInvoker.

public delegate void MethodInvoker(); // required

, EventArgs :

public class WmTcpEventArgs : EventArgs {

  private string data;

  public WmTcpEventArgs(string text) {
    data = text;
  }

  public string Data { get { return data; } }

}

. WmTcpEventArgs , - TextBox control:

private void NetworkResponder(object sender, WmTcpEventArgs e) {
  textBox1.Text = e.Data;
}

while(true) ,

private bool abortListener;

:

public void Listen() {
  listener.Start();
  while (!abortListener) {
    try {
      using (var client = listener.AcceptTcpClient()) {
        int MAX = client.ReceiveBufferSize;
        var now = DateTime.Now;
        using (var stream = client.GetStream()) {
          Byte[] buffer = new Byte[MAX];
          int len = stream.Read(buffer, 0, MAX);
          if (0 < len) {
            string data = Encoding.UTF8.GetString(buffer, 0, len);
            MethodInvoker method = delegate { NetworkResponder(this, new WmTcpEventArgs(data)); };
            abortListener = ((form1 == null) || form1.IsDisposed);
            if (!abortListener) {
              form1.Invoke(method);
            }
          }
        }
      }
    } catch (Exception err) {
      Debug.WriteLine(err.Message);
    } finally {
      listener.Stop();
    }
  }
}

, - , TcpListener.

+2

All Articles