ASP. NET uses simple chat room programs written by applications and session objects, and simple session chat rooms

Source: Internet
Author: User

ASP. NET uses simple chat room programs written by applications and session objects, and simple session chat rooms

ASP. Net has two important objects: application Object and session object.

Application: the object that records Application parameters. This object is used to share Application-level information.

Session: record the variable objects on the browser, used to store variables or objects of cross-page programs.

To be honest, I wrote asp.net for almost a year, and the application object has never been used. I read the book and wrote a simple chat room program based on the characteristics of the two objects. It is really very simple.

My idea is that there are two pages: Default Page and ChatRoom page. The page layout

Default Page:

ChatRoom page:

 

The general idea is that when logging on to the Default page, the entered nickname is saved to the session object, and the ChatRoom page is jumped to, and the session key is "nickname" is saved to the application object. Traverse the application object and add the nickname of the online person to The listbox on the left. The appliaction object is used in the Session_Start and Session_End methods to + 1 for the key "count", and-1 is used to record the current number of online users. Use the application Object key "content" to store chat records.

The code below

Global. asax:

Copy codeThe Code is as follows:
Protected void Application_Start (object sender, EventArgs e)
{
Application ["count"] = 0;
Application ["content"] = "Chat History \ n ";
}

Protected void Session_Start (object sender, EventArgs e)
{
Application. Lock ();
Application ["count"] = (int) Application ["count"] + 1;
Application. UnLock ();
}
Protected void Session_End (object sender, EventArgs e)
{
Application. Lock ();
Application ["count"] = (int) Application ["count"]-1;
Application. UnLock ();
}

Default. aspx:

Copy codeThe Code is as follows:
Protected void button_login_Click (object sender, EventArgs e)
{
If (! String. IsNullOrEmpty (textbox_nickname.Text ))
{
Session ["nickname"] = textbox_nickname.Text;
}
Response. Redirect ("ChatRoom. aspx ");
}

ChatRoom. aspx:

Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
Label_count.Text = "the current number of online users is" + Application ["count"]. ToString () + "person ";
If (! IsPostBack)
{
If (Session ["nickname"]! = Null)
{
Application. Add (Session ["nickname"]. ToString (), Session ["nickname"]);
}
Textbox_records.Text = Application ["content"]. ToString ();
}
Listbox_usernames.Items.Clear ();
Foreach (string str in Application. Contents)
{
If (! Str. Equals ("content ")&&! Str. Equals ("count ")&&! Str. Equals ("name "))
{
Listbox_usernames.Items.Add (new ListItem (Application [str]. ToString (), Application [str]. ToString ()));
}
}
}

Protected void button_send_Click (object sender, EventArgs e)
{
If (Session ["nickname"]! = Null)
{
Application ["content"] + = (Session ["nickname"]. ToString () + "said:" + textbox_sendmsg.Text + "\ n ");
Textbox_records.Text = Application ["content"]. ToString ();
}
}

Protected void button_exit_Click (object sender, EventArgs e)
{
Application. Remove (Session ["nickname"]. ToString ());
Application ["count"] = (int) Application ["count"]-1;
Response. Redirect ("WebCounter. aspx ");
}

This simple chat room is complete. During local use, it seems that no new session will be created in a browser. You need to log on to different browsers to see the effect.

Note that when you exit the chat room, you need to remove the value of the application key "nickname", that is, the current session ["nickname. Otherwise, when you refresh the listbox, you will find that the exit nickname still exists.

At the same time, you also need to set the key to "count" of the application Object-1. Maybe you want to ask, isn't it already-1 in the Session_End method? I'm not sure about this. There may be two reasons. I don't know which one is it? Hope you can give me some advice.

1. The session has not expired. I just killed the corresponding key in the application as the session object, but I did not clear the real session. Therefore, the Session_End method is not called. (But you may ask, isn't it OK if you leave the current session ["nickname"] object empty? I tried this, but the count does not have-1 .)
2. Is it because I am using two local browsers to perform this chat?

In some special cases, the application object is very helpful to us, so I don't need to talk about the session. It is definitely something we often use.


Several Problems about the application object and session Object in ASP

Several built-in objects of ASP. NET
Introduction to built-in ASP. NET objects 0FL. N ^ o & y' Sh
1. Response-r # BW & x) tOEb
2. Request
E5B y & z7P, [; '3. Server _ 8iud3DiN @
4. Application/f3q' \-f ZA
5. Session! A C * Q] e8a2VF # g
6. Cookie @ 8JGk

The 8sJT0 @ S "} M8 'W Request object mainly allows the server to obtain some data from the client browser, including parameters, cookies, and user authentication transmitted from HTML forms using the Post or GET methods. Because the Request object is a member of the Page object, it can be directly used without any declaration in the program. Its class name has many HttpRequest attributes, but there are few methods, and only one BinaryRead ()] i} 3lk % B: r'f
| 2d9TZ, |
1. Use the Request. Form attribute to retrieve data! Tj % L2} rf
Use this attribute to read Form data between <Form> </Form>. Note: Set the submission method to [color = red] Post [/color].
Em/eM6H (compared with the Get method, yT can send a large amount of data to the server using the Post method.
^ 2 }~ Z-bo U (aa + I} F8m9G. U
2. Use the Request. QueryString attribute to obtain data
The QuerySting attribute of the lKQ v "c6 {Request object can be used to obtain a set of HTTP query string variables. Through this attribute, we can read the address information localhost/aaa. aspx? Uid = tom & pwd = abc indicates the data marked as the red part. Note: Set the submission method to [color = red] Get [/color].
@; ^ Of '@ 7X P. Y5T} R$} # N
3. Problem: Request. Form is used when the Form submission method is Post, while Request. QueryString is used when the Form submission method is Get. If an error is used, no data is obtained. Solution: Use the Request ("element name") to simplify the operation.
X1VUC Q $ E! F @ 3 S, P. oZ T [VWQz
4. Request. ServerVariables ("environment variable name ")~; J xT "E
Similarly, UserHostAddress, Browser, Cookies, ContentType, IsAuthenticated Item, Params. t # kII + D

. VVr9K5U2K o accept ----------------------------------------------------------------------------------------------------------
} D6c _: x0Z ^ + [.] 8 | (v + rAaf, B
Response object language outputs data to the client, including outputting data to the browser, redirecting... the remaining full text>

Differences and relationships between Application objects, Session objects, and Cookie objects

The first floor is very powerful ....

Application is used to save the data information shared by all users. If the stored data does not change or rarely change during the lifetime of the Application, use it. However, there is a web. config in asp.net, which may be better. To use the application, you must consider that any write operation must be completed in the application_onstart event (Global. asax. Although the application. lock and application. unlock methods are used to avoid Operation synchronization, They serialize application requests, which may cause performance bottlenecks when the Website access volume is large. Therefore, it is best not to use it to access large datasets.
Usage:
// Store information
Application ["test"] = "100 ";
// Read
String test = Application ["test"]. ToString ();

Session is used to save the dedicated information of each user. The lifetime of Session is the duration of the user's sustained request plus a period of time (which can be set in web. config. The default value is 20 minutes ). The Session information is stored in the server's memory. Of course, you can set the method for saving the Session information (such as the information stored in the SQL database ). Since the user stops using the program and it remains in the memory for a period of time, the efficiency of using the Session object to save user data is very low. For a small amount of data. Session is a good choice.
// Save
Session ["user"] = "majcms ";
// Obtain
String username = Session ["user"]. ToString ();

Cookie is used to save the request information of the client browser requesting the Server Page. programmers can also use it to save non-sensitive content. You can set the Save time as needed. If no Cookie expiration time is set, it will only be saved to the browser. If the Cookie is set to Min Value, it never expires. The Cookie storage capacity is limited. Generally, the maximum size of a browser is 4096 bytes. Therefore, it cannot be used to store large amounts of data. Since not all browsers support cookies and they are saved in plain text, it is best not to save sensitive content. Otherwise, network security is affected.
// Save
Response. Cookies ["name"]. Value = "majcms ";
// Obtain
String username = Response. Cookies ["name"]. Value;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.