views:

73

answers:

2

hello everybody,

i am working on a project which uses socket programming.but when using the same socket for multiple number of times even after closing down the listener() at each time i use the socket.when i run the application it gives the error as the above.i am really worried about it.if somebody can help me out.thanks in advance.

+1  A: 

You are sure that you are picking a port that's unique right?

Have you tried to just use the port once?

Make sure you are truly disposing of connection objects etc before you reopen the socket. Hard to know without more implementation details.

msp
A: 

Here is code that i am using, i am closing all connections properly

TcpClient tcpClient; TcpListener tcpListener; 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 { tcpClient.ReceiveTimeout = 1; tcpClient = tcpListener.AcceptTcpClient(); } catch (Exception ex) { tcpClient.Close(); tcpListener.Stop(); } NetworkStream networkStream = tcpClient.GetStream(); byte[] bytes = new byte[networkStream.Length]; 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;
Mohammad Tanveer