Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am new to C# and .net core. I am building a billing program where PBX send data as client on defined TCP port .
I created project in C# and it is working fine, means I can listen on port and get data from client.
But for some random reason port stop listening and I can confirm this from window server resource monitor Network --> Listening Ports.
I can also confirm there is port overlapping means no other software use that port.
But if I restart service it start to listen on port again.
I want port to never stop listen on that TCP port, and if for any reason it stop , it should automatically start to listen again.
Client software and billing program are installed on same PC.

What I have tried:

<pre lang="C#"><pre>
using CDR.Models;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace CDR.Helpers
{
    /// <summary>
    /// Active or Passive.
    /// </summary>
    public class CDRServer
    {
        public static void Listen()
        {
            Logger.Log("Starting 3cX Listener");

            TcpListener server = null;
            try
            {
                // Set the TcpListener on port 13000.
                Int32 port = 5015;

                // IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                // if (!ipHostInfo.AddressList.Any(d => d.AddressFamily == AddressFamily.InterNetwork))
                //   return;
                //IPAddress ipAddress = ipHostInfo.AddressList.FirstOrDefault(d => d.AddressFamily == AddressFamily.InterNetwork);//IPAddress.Parse("127.0.0.1");//

                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(ipAddress, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[1024]; //this can be received.  //INVESTIGATE

                //100KB

                String data = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.WriteLine($"Waiting for a connection...  on {ipAddress.ToString()} and {port.ToString()}");
                    Logger.Log($"Waiting for a connection...  on {ipAddress.ToString()} and {port.ToString()}");
                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");
                    Logger.Log("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);

                        Console.WriteLine("Received: {0}", data);

                        //process the received call data and then save it to the database. 
                        Logger.Log($"Received: {data}");

                        try
                        {
                            CDRModel cdr = new CDRModel();
                            var datasplit = data.Split(',');

                            cdr.historyidofthecall = datasplit[0];
                            cdr.callid = datasplit[1];
                            cdr.duration = datasplit[2];

                            Logger.Log($"Before Date: {DateTime.Parse(datasplit[3]).ToString()}");
                            cdr.timestart = DateTime.Parse(datasplit[3]);//.Zone().AddHours(-3);
                            Logger.Log($"After Date: {cdr.timestart.ToString()}");

                            if (!string.IsNullOrEmpty(datasplit[4]))
                            {
                                cdr.timeanswered = DateTime.Parse(datasplit[4]);//.Zone().AddHours(-3);
                            }
                            cdr.timeend = DateTime.Parse(datasplit[5]);//.Zone().AddHours(-3);

                            cdr.reason_termination = datasplit[6];
                            cdr.from_no = datasplit[7];
                            cdr.to_no = datasplit[8];
                            cdr.from_dn = datasplit[9];
                            cdr.to_dn = datasplit[10];
                            cdr.dial_no = datasplit[11];
                            cdr.reason_changed = datasplit[12];
                            cdr.final_number = datasplit[13];
                            cdr.final_dn = datasplit[14];
                            cdr.from_type = datasplit[15];
                            cdr.missed_queue_calls = datasplit[16];
                            cdr.chain = datasplit[17];
                            //cDR.Chain = dataSplit[19];

                            // Process the data sent by the client add to the database.
                            //using (var context = new MySqlContext())
                            //{
                            //    context.CDRs.Add(cDR);
                            //    context.SaveChanges();
                            //}

                            //Post object to external server. 
                            Logger.Log(JsonConvert.SerializeObject(cdr));

                            //var url = Environment.GetEnvironmentVariable("cdrlink");
                            if (!File.Exists("Db.txt"))
                                Console.WriteLine("Db.txt file not found");
                            var url = File.ReadAllText(@"Db.txt");
                            Logger.Log(url);
                            RestClient client2 = new RestClient(url);
                            
                            RestRequest request = new RestRequest(Method.POST);
                            request.AddParameter("application/json", JsonConvert.SerializeObject(cdr), ParameterType.RequestBody);
                            var response = client2.Execute(request);
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(ex);
                        }


                        //byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        //stream.Write(msg, 0, msg.Length);
                        //Console.WriteLine("Sent: {0}", data);
                    }

                    // Shutdown and end connection
                    client.Close();
                    Logger.Log("Client Closed");

                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
                Logger.Log(e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
                Logger.Log("Server Stopped");
            }


            Console.WriteLine("\nHit enter to continue...");
            Console.Read();

        }

    }

}
Posted
Updated 11-Mar-22 22:23pm

Try like in this example: tcp-listener-with-net-core[^]
After the AcceptTcpClient() it uses another While loop.
 
Share this answer
 
You already posted this at C# TcpListener listen forever - .NET (Core and Framework) Discussion Boards[^]. Please do not repost.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900