Title: Fetching data from C# Asp Server with a Windows Service
Tags: c#;tcp
Question: I have a Windows service that loops every second and polls a server (in ASP WebForms Framework 4, not MVC) for new informations by connecting in HTTPS and sending a 'home-made' ciphered data and receiving the response, ciphered as well.

The issues of this method are both resource and time consumptions. 

Every second, the service has to create a connection, cipher a data and decrypt the response.

I was thinking about using TcpConnections to :


Connect to the server once and for all
Receive new informations from the server when they come and treat them locally in my service


I was trying to do so, like this :

Server side code (in the Global.asax for now)

```protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

   Task.Run(Run);
}

public static async Task Run()
{
    try
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8080); //Any IPAddress that connects to the server on any port
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Initialize a new Socket

        socket.Bind(ip); //Bind to the client's IP
        socket.Listen(10); //Listen for maximum 10 connections
        Console.WriteLine("Waiting for a client...");
        Socket client = socket.Accept();
        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

        string welcome = "Welcome"; //This is the data we we'll respond with
        byte[] data = new byte[1024];
        data = Encoding.ASCII.GetBytes(welcome); //Encode the data
        client.Send(data, data.Length, SocketFlags.None); //Send the data to the client
    } 
    catch(Exception e)
    {
        Console.WriteLine($"Error : {e.Message} {e.StackTrace}");
    }
}
```

(a method is also created to send data to the client out of the task above).

Client side Code

```const int PORT_NO = 8080;
const string SERVER_IP = "localhost";

static void Main()
{

    IPEndPoint ip = new IPEndPoint(IPAddress.Parse("(902)965-4041"), 8080);

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

    try
    {
        server.Connect(ip); //Connect to the server
    }
    catch (SocketException e)
    {
        Console.WriteLine($"Unable to connect to server : {e.Message} {e.StackTrace}");
        return;
    }

    Console.WriteLine("Type 'exit' to exit.");
    while (true)
    {
        string input = "aaaaa";
        if (input == "exit")
            break;
        server.Send(Encoding.ASCII.GetBytes(input)); //Encode from user's input, send the data
        byte[] data = new byte[1024];
        int receivedDataLength = server.Receive(data); //Wait for the data
        string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); //Decode the data received
        Console.WriteLine(stringData); //Write the data on the screen
        System.Threading.Thread.Sleep(5000);
    }


}
```

The connection seems to work for the first message, I manage to send/receive data from the client and the server. But then the 'client' server-side object disposes itself (becomes null).


Is it because the Tcp Connection is not persistant ?


If so, I tried to add this line :

```socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
```

But then I get the following exception :

```An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call
```


How can I prevent my TcpConnection from closing after the client receives the data sent from the server ? 
Is there a more secure way to exchange data from server to client ? Maybe by using an SSL TLS Connection like this : C# TcpClient reading multiple messages over persistent connection ? I was thinking of SignalR but I'm not sure it works on Framework 4 Web App environment


Comment: SignalR is a nice workaround and is available with the .NET 4.0 framework  -> official documentation https://msdn.microsoft.com/en-us/library/microsoft.aspnet.signalr(v=vs.100).aspx

Comment: Is there a specific reason you are writing your own custom server and not just using the built in WebApi/MVC 5 services that come with modern .net?

Comment: The reason is mostly historical, this server was designed 5 years ago and served as interface between smartphones and software clients (based on encrypted XML exchanges)

Comment: Thanks a lot. Seems like SignalR was what i was looking for after all!

Comment: the sockets are created in your methods and as soon as the methods terminate the sockets will close.  The sockets need to be in global space to stay open.  You application also needs to block so it doesn't close after processing one message.



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 5, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:11/07/17', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<c#><tcp>', 'Title': 'Fetching data from C# Asp Server with a Windows Service', 'ViewCount': 58, 'id': 47160674, 'user_AboutMe': '', 'user_AccountId': 941945.0, 'user_DisplayName': 'Thordax', 'user_Reputation': 1633.0, 'user_Views': 145.0, 'user_id': 969881.0}}