ASP Tutorial: The use of global.asa files and chat programs

Source: Internet
Author: User
Tags servervariables

In the previous article, the author gave you a detailed introduction of two very useful ASP built-in object application and Session of the use of the method. Because both of the OnStart, OnEnd event scripts must be declared in the Global.asa file, this article will give you a detailed description of how the Global.asa file is used. To enable you to master the knowledge that has been learned so far, this article will also cite an ASP Chat procedure for your reference.

A lot of friends have recently written to me about why the first two-year paradigm program runs with such errors. First of all, I would like to declare that these procedures are written by myself, before the "factory" has passed the qualified inspection, there is no "fake and shoddy products". :) Since cookies are used to record customer information in the program, the program will not function properly if you do not set the Accept cookie in the browser. In addition, the method used by the program to record customer information on the client's cookie is Response.cookie, which must be written before the first < html> tag in the ASP file, because the cookie is sent to the guest as part of the header information for the HTTP transmission If the HTTP header information has been transmitted to the client before using Response.cookie, the following error will occur: "The HTTP header has been written to the customer's browser." Any modification of the HTTP header must precede the content of the page. ", maybe some friends did not notice when the Clipboard, upset the sequence of the program, or mistakenly added HTML code before the ASP sample program, resulting in a program run error. Therefore, I suggest that on the one hand, when you run the routine for the first time do not make any changes to the program, as far as possible to understand the program based on gradual improvement, on the other hand, when running the ASP program at least in the browser to select the acceptable cookie, otherwise, once the ASP program used a cookie or Session, They will not function properly.

Let me show you how to use the Global.asa file.

What is a Global.asa file? It is actually an optional file where the program writer can specify the event script and declare an object with session and application scope. The contents of the file are not intended for display to the user, but are used to store event information and objects that are used globally by the application. The name of the file must be global.asa and must reside in the root directory of the application. There can be only one Global.asa file per application.

In the Global.asa file, the server returns an error if the contained script is not encapsulated with the < script> tag, or if the defined object does not have a session or application scope. We can write scripts contained in the Global.asa file in any language that supports scripting. If multiple events use the same scripting language, they can be organized in a set of < script> tags.

The procedure declared in the Global.asa file can only be called from one or more scripts that are related to Application_OnStart, Application_OnEnd, Session_OnStart, and Session_OnEnd events. In ASP pages for ASP-based applications, they are not available. If you want to share procedures between applications, you can declare them in a separate file, and then use the server-side containment (SSI) statement to include the file in the ASP program that called the procedure. Typically, the extension of the containing file should be. Inc.

The following is a very standard Global.asa file:

< SCRIPT language= "VBScript" runat= "Server" >
\ ' Session_OnStart run when the customer first runs any page in an ASP application
\ ' Session_OnEnd run when a client's session times out or exits the application
\ ' Application_OnStart run when any customer first accesses the home page of the application
\ ' Application_OnEnd run when the Web server for the site is shut down
</script>
< SCRIPT language= "VBScript" runat= "Server" >
Sub Application_OnStart
Visitorcountfilename = Server.MapPath ("/ex2") + "\\VisitCount.txt"
Set FileObject = Server.CreateObject ("Scripting.FileSystemObject")
Set out= Fileobject.opentextfile (Visitorcountfilename, 1, false, False)
Application ("visitors") = Out.readline
Application ("visitorcountfilename") = Visitorcountfilename
End Sub
\ ' =========================================================
SUB Application_OnEnd
Set fileoutobject = Server.CreateObject ("Scripting.FileSystemObject")
Set out= fileoutobject.createtextfile (Application ("Visitorcountfilename"), True,false)
Out.writeline (Application ("visitors"))
End Sub
\ ' =========================================================sub Session_OnStart
Session.Timeout = 5
Application ("visitors") = Application ("visitors") + 1
Session ("ID") =session.sessionid
End Sub
</script>

In this Global.asa program, the ASP's file access component is involved, which provides methods, properties, and collections for accessing the file system. This will be discussed in later components of the ASP. Here, it plays the role of creating a new file on the server and writing to the file. This is actually an ASP page access to the Global file of the register application, first when the customer first visited the application's home page, the procedure Application_OnStart defines a new VisitCount.txt text file in the virtual directory specified on the server, and save the path and contents of the file in an application-level variable. When any one client accesses any page in an ASP application, the procedure Session_OnStart defines the value of the variable visitors at the application level to automatically add one. In this way, whenever a customer accesses a page, the variable visitors is automatically added to the function of the statistical Ctr. Since the value of the variable visitors is stored in the system memory, if the server is shut down or restarted, the data stored in the variable is automatically lost, so by defining the process Application_OnEnd, the data is written to the pre-established text file before the server shuts down or restarts. This ensures that when the server is started again, the Application_OnStart process can read the previous statistics from the VisitCount.txt file. Shanghai Treatment Impotence Hospital: http://www.edzl.cn/}

After this period of study, I believe that we have been able to use the more skilled in these ASP built-in objects to write some of the more simple ASP applications, do not underestimate what you now have mastered the basic knowledge of the ASP Oh! In fact, you have been able to develop some simple but useful ASP applications. Below I will give a very simple ASP WEB chat room program, you will find that the writing chat room turned out to be such an easy, easy thing. Perhaps friends have seen in some magazines how ASP chat programs are written, but the author wrote a simpler program here, using only one. ASP file. Please paste the following code into your Notepad and save it as chat.asp.

<%@ Language=vbscript%>
<%
Response.buffer=true \ ' Sets the output cache for displaying different pages.
On Error Resume Next \ ' Ignore program error section
If Request.ServerVariables ("request_method") = "GET" Then
\ ' Determine how the customer is requesting a WEB page
\‘------------------------
\ ' Client Login interface
\‘------------------------
%>
< form method= "POST" action= "chat.asp" >< p>
< input type= "text" name= "Nick" size= "value=" Nick "style=" < br>
< input type= "submit" value= "Enter chat room" name= "B1" style= "Color:rgb (255,255,0); font-size:9pt;
< p>< input type= "hidden" name= "Log" size= "$" value= "1" >< br></p>
</form>
<%
Response.End \ ' End of program processing
Else
Response.Clear \ ' Empty the contents of the cache
Dim talk
If Request.Form ("Nick") <> "then
\ ' Determine if the customer is in the chat interface
Session ("Nick") =request.form ("Nick")
End If
\‘------------------------\‘
Customer Chat Interface
\‘------------------------
%>
< form method= "POST" action= "chat.asp" name=form1>< p><%=session ("Nick")%> speak:< input type= "text" Name= "Talk" size= ">< br>"
< input type= "submit" value= "commit" Name= "B1" >
< input type= "reset" value= "Cancel" name= "B2" ></p>
</form>
< A href= "/asptest/shusheng/chat.asp" > Departure </a>< br>< br>
<%
If Request.Form ("log") <>1 Then
If Trim (Request.Form ("talk")) = "Then
\ ' Determine if the user has not entered any content
Talk=session ("Nick") & "Silence is gold." "
Else
Talk=trim (Request.Form ("Talk"))
\ ' Remove the space after the character
End If
Application.Lock
Application ("show") = "< table border=\ ' 0\ ' cellpadding=\ ' 0\ ' cellspacing=\ ' 0\ ' width=\ ' 85%\ ' >< tr>< TD Width=\ ' 100%\ ' bgcolor=\ ' #C0C0C0 \ ' ></td></tr>< tr>< td width=\ ' 100%\ ' >< font color=\ ' # 0000ff\ ' > From ' &request.servervariables ("REMOTE_ADDR") & "&session (" Nick ") &time&" say:</ Font> "&talk&" </td></tr>< tr>< TD width=\ ' 100%\ ' bgcolor=\ ' #C0C0C0 \ ' ></td> </tr></table>< br> "&application (" show ")
Application.UnLock
Response.Write Application ("show")
End If
End If
%>

The first time you run the chat.asp program, you will first see the following page:


After choosing your nick to enter the chat room, you will see the following page:


Enter the words you want to say, and the dialog will appear below the input box, such as:


Let's make a gradual analysis of this chat room program.

First, because all the customers in the chat room have to be able to share information, it is unavoidable to use object application with application-level variables, which is the key to building the chat program, where all the conversation data is stored in an application-level variable so that all the customers can read it. We can use the request object that we have learned to get the conversation that the customer entered, save it in the variable talk, and then put the value in the application-level variable show as follows:

<% application ("show") =talk&application ("show")%>

The next thing to consider is what to do when different customers are working with the Chat application at the same time. This problem is actually the same as the two users in the database write the same record at the same time, if two users simultaneously write to the same application-level variable, one user's modifications will be overwritten by another user's actions, so if the application Concurrent access to object data does not take some action, resulting in the submission of one user being overwritten by the submission of another user when two users attempt to submit to an ASP chat room application at the same time, disappearing before anyone who participates in the session sees it. To avoid such problems, we need to use the Lock property of the Application object to constrain only the current user to edit or increase the properties of the Application object, so that when the user starts to modify the application-level variable, the Application object is explicitly Unlocked, the properties of the Application object can only be edited by the user, and if other users request to edit the Application object at this time, those users will be queued up until the application is Unlock. As shown below:

Application.Lock
Application ("Show") =talk&application ("show")
Application.UnLock

Now that the core part of the entire program you've learned, here's how to save customer information, here we'll use a session-level variable, and the client's nick will be saved in session. Such as:

Session ("Nick") =request.form ("Nick")

Finally, we need to consider how to handle various events in only one. asp file, such as: Customer Login interface, customer chat interface. Since the first time a customer requests an. asp file, a simple HTTP GET method is used, but when the customer adds the data to the form field on the page and submits the form to itself, the. asp file is requested again, but this time the data is passed through the HTTP POST method. The way the file is requested can be determined in two ways. One is to test whether the Request.Form collection contains members, and if not, indicates that no data was sent to the form processing. The second is to use the Request.ServerVariables ("Request_method") variable. If the form is requested via HTTP get, the variable returns "get" and returns "POST" if the form is submitted for processing. Since the latter method is more straightforward in determining how files are requested, we use the following code to judge:

If Request.ServerVariables ("request_method") = "GET" Then

Since we set up the ASP cache, when the program determines that the page request is GET, the program runs Response.End to end all subsequent operations, otherwise runs Response.Clear, empties the contents of the cache, and continues the program's operation. This allows us to use the same. asp file to display different interfaces to the customer according to different circumstances.

OK, I have to this ASP Chat program core part to tell you, the rest of the details of the problem please yourselves read the program bar, in fact, there are many shortcomings of this program, the biggest problem is that I did not write automatic refresh function, so if you do not speak in Chat, That will not see what other customers have said. Chat in the Internet charm everyone is aware of, in fact, with the ASP also can do with IRC similar powerful features, of course, this need to write more code, if you are interested please write to me, I will gradually improve the level of this chat program in future articles, so that we have also passed the "Ope R "of Cain. Note: With this chat program, you can use to build a chat app on your PWS, just tell your friends about your IP address, such as http://202.96.210.33/asp/ chat.asp, you can chat on the Internet through your computer, very cool, do not believe you try!

ASP Tutorial: The use of global.asa files and chat programs

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.