views:

353

answers:

2

Hello All,

I am connecting to TCP/IP port in Asp.Net, basically i have attached a device on this port to which i am reading, it is working fine but on second time when tcp listener tries to start then it generates the above error. can any body guide me how can i get rid of this error here is my code that i am using to connect to TCP/IP port:

       try
        {                
            byte[] ipaddress = new byte[4];
            string ip = ConfigurationManager.AppSettings["IP"].ToString();
            string[] ips = ip.Split('.');
            ipaddress[0] = (byte)Convert.ToInt32(ips[0]);
            ipaddress[1] = (byte)Convert.ToInt32(ips[1]);
            ipaddress[2] = (byte)Convert.ToInt32(ips[2]);
            ipaddress[3] = (byte)Convert.ToInt32(ips[3]);
            int portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
            tcpListener = new TcpListener(new IPAddress(ipaddress), portNumber);
            tcpListener.Start();
            tcpClient = new TcpClient();
            tcpClient.NoDelay = true;
            try
            {
                System.Threading.Thread.Sleep(60000);
                tcpClient.ReceiveTimeout = 10;
                tcpClient = tcpListener.AcceptTcpClient();
            }
            catch (Exception ex)
            {
                tcpClient.Close();
                tcpListener.Stop();
            }
            NetworkStream networkStream = tcpClient.GetStream();
            byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
            try
            {
                networkStream.ReadTimeout = 2000;
                networkStream.Read(bytes, 0, bytes.Length);
            }
            catch (Exception ex)
            {
                tcpClient.Close();
                tcpListener.Stop();
            }
            string returndata = Encoding.Default.GetString(bytes);
            tcpClient.Close();
            tcpListener.Stop();

            return returndata.Substring(returndata.IndexOf("0000000036"), 170);
        }
        catch (Exception ex)
        {
            if (tcpClient != null)
                tcpClient.Close();
            tcpListener.Stop();
            LogError("Global.cs", "ReceiveData", ex);
            ReceiveData();
        }

when it comes on this line tcpListener.Start(); for second time then it generates that error "Only one usage of each socket address (protocol/network address/port) is normally permitted"

+1  A: 

You don't make use of the using keyword or finally blocks to ensure your resources are closed.

If there are exceptions anywhere in your code, the cleanup may not happen. Your multiple catch blocks may get all scenarios, but I can't easily tell by reading the code.

A generally preferred pattern for using resources that need to be cleaned up is:

using (MyResource res = new MyResource())
{
   // Do Stuff
}

if MyResource implements IDisposable, or

try
{
  MyResource res = new MyResource();
  // Do Stuff
} catch (Exception ex)
{
  // Whatever needs handing on exception
}
finally
{
  res.Close(); // Or whatever call needs to be made to clean up your resource.
}
Eric J.
A: 

If this is in a loop or something, note that if your code doesn't fire any exceptions, then the connection is not closed. It is only closed if there is an exception, which would be caught by the ending catch block

Earlz