0

How do I keep the value in a cookie or a header instead of session; I do not know how to keep socket data in session. I tried Application["socket"]="127.0.0.1:3306"; did not work

Session.Add("socket", sender);

Socket s = (Socket)Session["socket"];

 try
    {
        if (Request.HttpMethod == "POST")
        {
            String status = Request.QueryString.Get("status").ToUpper();
            if (status == "welcome")
            {
                try
                {
                    String ipnum = "127.0.0.1".ToUpper();
                    int port = int.Parse("3306");
                    IPAddress ip = IPAddress.Parse(ipnum);
                    System.Net.IPEndPoint remoteEP = new IPEndPoint(ip, port);
                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sender.Connect(remoteEP);
                    sender.Blocking = false;
                    Session.Add("socket", sender);
                    Response.AddHeader("stat", "hello");
                }
                catch (Exception err)
                {
                    Response.AddHeader("warn", err.Message);
                    Response.AddHeader("stat", "FAIL");
                }
            }
            else if (status == "goodbye")
            {
                try {
                    Socket s = (Socket)Session["socket"];
                    s.Close();
                } catch (Exception err){

                }
                Session.Abandon();
                Response.AddHeader("stat", "hello");
            }
muhammad
  • 13
  • 2

1 Answers1

1

Depends on what it is, where you want to access it and why. If it's just a matter of having it in your backend, then stick to the session.

Important:

You can't add the Socket object as a cookie or header. Cookies and headers are strings. The socket object is much more than that and even if you could serialize it and deserialize it, it wouldn't refer to the same resources and/or connection.

If you want to share a value (that makes sense) with the client, you can add it to a cookie like this:

HttpContext.Response.Cookies.Append("first_request", DateTime.Now.ToString());

I can see that you already know how to add a header, so I won't go in there.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Well, can we not write socket to text file and read – muhammad Sep 13 '20 at 09:55
  • No, you can't. You can write the socket configuration, but not what the `Socket` class represents – Athanasios Kataras Sep 13 '20 at 09:59
  • How can I remove the session completely – muhammad Sep 13 '20 at 10:12
  • Why do you want that? You will need to find a way to keep the `Socket` object in memory in the backend app domain. Your best bet, is to let another process manage the network connections. You are going to have issues with app pool restarts, etc. But we'd really require the scenario to make specific suggestions. – Athanasios Kataras Sep 13 '20 at 10:22