0

I am creating a TCP Server/Client. As for this project, i need to only run this function for 60 seconds, and after that, it will terminate. Can someone guide me to fix this code?

public static void SendTCPServer(string content)
    {
        Stopwatch timer = new Stopwatch();
        timer.Start();

        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
                               8080);

        Socket newsock = new
            Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

        newsock.Bind(ipep);
        newsock.Listen(10);
        while (timer.Elapsed.TotalSeconds < 60)
        {
            Console.WriteLine("Waiting for a client...");
        Socket client = newsock.Accept();
        IPEndPoint clientep =
                     (IPEndPoint)client.RemoteEndPoint;


            Console.WriteLine("Connected with {0} at port {1}",
                            clientep.Address, clientep.Port);


            string welcome = content;
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length,
                              SocketFlags.None);

            Console.WriteLine("Disconnected from {0}",
                              clientep.Address);
            client.Close();
            newsock.Close();
            return;
        }
        timer.Stop();
        //client.Close();
        newsock.Close();
        return;
    }
encikpiee
  • 69
  • 10
  • Assuming you have incoming connections (since you are using blocking calls), I would have thought your code sufficient. What actually happens? If you have no incoming peers, then of course your code will block possibly exceeding the timeout. Consider using the `async` version? –  Jun 26 '18 at 06:18
  • @User453465436754 This code works. I just want this code to stop after 60 seconds, if there is no incoming peers, so that, the other code will run normally without hanging. If i'm not mistaken, async is supported on NET 4.5 and above. Some of my libraries is limited to NET 4.0. – encikpiee Jun 26 '18 at 06:24
  • Consider this: https://stackoverflow.com/questions/1062035/how-to-configure-socket-connect-timeout – PepitoSh Jun 26 '18 at 06:29
  • You don't have to use `async/await`. You can use the old school `Beginxxxx()` methods which return an `IAsyncResult`. –  Jun 26 '18 at 08:28

1 Answers1

0

You can use thread for this.

 public class Parameters
 {
    public Socket _socket;
    public string content;
 }

//calling part
  Thread listenerThread = new Thread(new ParameterizedThreadStart(SendTCPServer));
        Socket newsock = new
           Socket(AddressFamily.InterNetwork,
                       SocketType.Stream, ProtocolType.Tcp);
        listenerThread.Start(new Parameters { _socket = newsock, content = "Welcome" 
 });

        Thread.Sleep(60000);
            newsock.Dispose();
//calling part end
 public static void SendTCPServer(object obj)
    {
        try
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();

            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
                                   8080);

            Parameters param = obj as Parameters;


            Socket newsock = param._socket;
            newsock.Bind(ipep);
            newsock.Listen(10);
            while (timer.Elapsed.TotalSeconds < 60)
            {
                Console.WriteLine("Waiting for a client...");
                Socket client = newsock.Accept();
                IPEndPoint clientep =
                             (IPEndPoint)client.RemoteEndPoint;


                Console.WriteLine("Connected with {0} at port {1}",
                                clientep.Address, clientep.Port);


                string welcome = param.content;
                data = Encoding.ASCII.GetBytes(welcome);
                client.Send(data, data.Length,
                                  SocketFlags.None);

                Console.WriteLine("Disconnected from {0}",
                                  clientep.Address);
                client.Close();
                newsock.Close();
                return;
            }
            timer.Stop();
            //client.Close();
            newsock.Close();
            return;
        }
        catch (Exception ex)
        {


        }

    }
  • Works, but is kinda brute-force with the call to `Dispose` after 60 seconds. Consider shutting down gracefully –  Jun 26 '18 at 07:39
  • you can add extra control or check if there is a connection. – Sea cucumber Jun 26 '18 at 08:12
  • Not sure if you realise but as soon as you execute `newsock.Accept();`, the thread will block until a connection comes along and will most likely just end up throwing an exception due to your call to `Dispose()` after 60 seconds –  Jun 26 '18 at 08:22
  • actually, this is what i need and it works! only 1 or no client will connect to this server for a short period of time. thank you @Seacucumber – encikpiee Jun 26 '18 at 08:34