none
Only one usage of each socket address (protocol/network address/port) is normally permitted stopping service RRS feed

  • Question

  • I have developed a windows service which listens a TCP port for the data and insert that data in sql server, now the problem is I am calling the TCP listener method in every 1 minute so if in that period of time if it gets a ready client then it accepts the data but if it don't gets the data then it throws the exception in every 1 minute  and never listens the port after that. I am new to windows service and socket programming please help me, I am posting here my code and exception:

    Exception:

    Only one usage of each socket address (protocol/network address/port) is normally permitted

    protected override void OnStart(string[] args)
    {
         
        TraceService("start service");     
        timer.Elapsed += new ElapsedEventHandler(SocketService);
    
                timer.Interval = 60000;
                timer.Enabled = true;
    }
    
     private void SocketService(object source, ElapsedEventArgs e)
            {
                //timer.Enabled = false;
                TcpListener server = null;
                try
                {
                   
                    Int32 port = 10912;
                    IPAddress localAddr = IPAddress.Parse("192.168.1.17");
    
                    // TcpListener server = new TcpListener(port);
                    server = new TcpListener(localAddr, port);
    
                    // Start listening for client requests.
                    server.Start();
    
                    // Buffer for reading data
                    Byte[] bytes = new Byte[256];
                    String data = null;
                  
                    // Enter the listening loop. 
                    while (true)
                    {
                        TraceService("Waiting for a connection... ");
    
                        // Perform a blocking call to accept requests. 
                        // You could also user server.AcceptSocket() here.
                        
                        TcpClient client = server.AcceptTcpClient();
                        TraceService("Connected!");
    
                        data = null;
    
                        // Get a stream object for reading and writing
                        NetworkStream stream = client.GetStream();
    
                        int i;
    
                        // Loop to receive all the data sent by the client. 
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            // Translate data bytes to a ASCII string.
                            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                            TraceService(data.ToString());
    
                            // Process the data sent by the client.
                            //data = data.ToUpper();
    
                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
    
                            // Send back a response.
                            //stream.Write(msg, 0, msg.Length);
                            //TraceService(data.ToString());
                        }
    
                        // Shutdown and end connection
                        client.Close();
                    }
                        
                   // server.Stop();
                    
                }
                catch (SocketException ex)
                {
                    TraceService("Exception!!");
                    TraceService(ex.Message);
                }
                finally
                {
                    // Stop listening for new clients.
                    server.Stop();
                }
            }

    Please Help me! thanks in Advance!!


    • Edited by Amit_wdh Friday, April 4, 2014 10:59 PM
    Friday, April 4, 2014 10:57 PM

Answers

  • How many clients are going to connect to the Server?  the code is slightly different for more than one client.  The "target actively refused it" can be caused by credential issues, firewalls, virus checker, and coding errors. 

    The accept method can be sync (blocking) or async (non-blocking).  You are using the sync version which will block until the connection is made from the client.  The accept method will wait for the connection to be made  and then return.  I didn't notice before but the Accept should be outside the while loop.  You will only get one Accept when the connections made.

    You close connection is outside the while loop.  There are two methods for TCP connections

    1) Open and close the connection for each message send.  Then the Accept and close are both inside the while loop.

    2) Keep connection open forever.  Then the Accept and close are both outside the while loop.

    You can't have the Accept inside the while and the close outside the while (or the opposite).

                   TcpClient client = server.AcceptTcpClient();
                   while (true)
                   {
    
                   }
    


    jdweng

    • Marked as answer by Amit_wdh Saturday, April 5, 2014 9:38 PM
    Saturday, April 5, 2014 3:35 PM

All replies

  • You don't need the timer.  Once you start the service it will automatically run forever.  You are getting the error because you can only have one listener for each IP address - Port number combination.  The listen works the first time you call the routine, but will get an error the 2nd time because the port number is already being used.

    jdweng

    Saturday, April 5, 2014 5:34 AM

  • Thank you Joel for your guidance but as you said I should simply call   this Scoketservice() method without timer, I tried it but  then it doesn't let the service start because

     TcpClient client = server.AcceptTcpClient();

    this code line waits for the client request and if it doesn't get the appropriate client request then it does not allow service to start it goes in waiting state.

    Please help me!

     
    Saturday, April 5, 2014 1:49 PM
  • When you start a connection the server/listener starts first and waits for the client to connect.  You will not get to the while loop until you get the client to connect.  This is normal.  You can't read any thing from the client until the connection is made.

    jdweng

    Saturday, April 5, 2014 2:57 PM
  • Then how can it be done. My main goal is to develop a windows service which is able to listen the Tcp port for incoming data when data is available there on client. Now I have also used server.Pending() method that let service start but after once it start it is not able to listen the port, I have tested it by sending data on port using Tcp client but it says "No connection could be made because the target machine actively refused it". So it is clear from exception that created server is not working.

    Please help

    Saturday, April 5, 2014 3:12 PM
  • How many clients are going to connect to the Server?  the code is slightly different for more than one client.  The "target actively refused it" can be caused by credential issues, firewalls, virus checker, and coding errors. 

    The accept method can be sync (blocking) or async (non-blocking).  You are using the sync version which will block until the connection is made from the client.  The accept method will wait for the connection to be made  and then return.  I didn't notice before but the Accept should be outside the while loop.  You will only get one Accept when the connections made.

    You close connection is outside the while loop.  There are two methods for TCP connections

    1) Open and close the connection for each message send.  Then the Accept and close are both inside the while loop.

    2) Keep connection open forever.  Then the Accept and close are both outside the while loop.

    You can't have the Accept inside the while and the close outside the while (or the opposite).

                   TcpClient client = server.AcceptTcpClient();
                   while (true)
                   {
    
                   }
    


    jdweng

    • Marked as answer by Amit_wdh Saturday, April 5, 2014 9:38 PM
    Saturday, April 5, 2014 3:35 PM
  • I've used the code from here:

    http://www.daniweb.com/software-development/csharp/code/422291/user-friendly-asynchronous-event-driven-tcp-client

    This makes it easy to listen to TCP ports because it will fire an event when data is received on the port. You simply have to handle the event to process the incoming data. It works great!


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Saturday, April 5, 2014 3:35 PM
    Moderator
  • Thank you so much Joel
    Saturday, April 5, 2014 9:39 PM