Search code examples
c#asp.nettimerviewstateudpclient

Udpclient variable keeps resetting to Null ASP.NET


I am working on a small project that uses an asp website as a UDP listener. The problem is that I use timer and as a result, it loads the page every time causing udpclient to reconnect to the same port again and again, which throws an exception.

I usedif (!IsPostBack) under protected void Page_Load(object sender, EventArgs e) to use it once, but as it is a global variable, it makes it null regardless.

I have heard about ViewState, but I do not know how to employ it for udpclient value.

below is my code:

private const int listenPort = 6011;

IPEndPoint groupEP;
UdpClient listener;

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        listener = new UdpClient(listenPort);

        groupEP = new IPEndPoint(IPAddress.Any, listenPort);

    }

}


protected void Timer1_Tick(object sender, EventArgs e)
{
    Recive();
}

public void Recive()
{



    byte[] bytes = listener.Receive(ref groupEP);


    var width = 100; // for example
    var height = 100; // for example
    var dpiX = 96d;
    var dpiY = 96d;
    var pixelFormat = PixelFormats.Pbgra32; // for example
    var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8;
    var stride = bytesPerPixel * width;

    var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
                                     pixelFormat, null, bytes, stride);



    System.Drawing.Bitmap bitmap1;
    using (MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();

        enc.Frames.Add(BitmapFrame.Create(bitmap));
        enc.Save(outStream);
        bitmap1 = new System.Drawing.Bitmap(outStream);

        bitmap1.Save(HttpContext.Current.Server.MapPath("/image/bitmap.png"));
        Image1.ImageUrl = ("/image/bitmap.png");
    }


}

Solution

  • It makes perfect sense that the value is null on PostBacks. This is a fundamental concept in ASP.NET - if you don't persist something in your page, the next time the page loads, it will be null. The reason things like TextBoxes or other controls persist their values is because ASP.NET is doing some magic behind the scenes and serializing the control's values to ViewState which gets sent along with your HTML in the response to the client. Then when a PostBack happens, the values are sent back from the client in the HTTP request, and values are re-loaded from ViewState to your controls as part of the ASP.NET page life cycle.

    There are several methods for persisting. One person in the comments mentioned storing your variable as static, which you should not do (unless you want every single page hit by every single person that loads it to have access to the very same variable at the same time, thus introducing concurrency issues to deal with).

    In your situation, I would recommend using Page.Session which persists the variable server-side only (e.g. no client serialization). This variable persisted is on a per-session basis, so two different users will not be able to access the same variable, as opposed to the suggestion to use static. Something like this:

    if (!IsPostBack)
    {
        listener = new UdpClient(listenPort);
        Session["listener"] = listener;
    }
    else
    {
        listener = (UdpClient)Session["listener"];
    }