I want to keep it in cookie instead of session

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");
            }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x