可能朋友們已經在一些雜志上看到過 ASP 聊天程序的編寫方法,但作者在這里自己寫了一個更簡單的程序,僅僅使用了一個 .asp 文件。請將以下代碼剪貼到記事簿并保存為chat.asp。
< %@ Language=VBScript %>< %Response.Buffer=true ' 設置輸出緩存,用于顯示不同頁面。On error resume next ' 忽略程序出錯部分If Request.ServerVariables("Request_Method")="GET" then' 判斷客戶是以什么方式請求 WEB 頁面'------------------------' 客戶登陸界面 '------------------------%>< form method="POST" action="chat.asp">< p>< input type="text" name="nick" size="20" value="nick" style="background-color: rgb(192,192,192)">< br>< input type="submit" value=" 進入聊天室 " name="B1" style="color: rgb(255,255,0); font-size: 9pt; background-color: rgb(0,128,128)">< p>< input type="hidden" name="log" size="20" value="1">< br>< /p>< /form>< %Response.End ' 結束程序的處理ElseResponse.clear ' 清空緩存中的內容dim talkIf Request.Form("nick")<>"" then' 判斷客戶是是否在聊天界面中 Session("nick")=Request.Form("nick")End If'------------------------'客戶聊天界面 '------------------------%>< form method="POST" action="chat.asp" name=form1> < p>< %=Session("nick")%> 說話:< input type="text" name="talk" size="50">< br>< input type="submit" value=" 提交 " name="B1">< input type="reset" value=" 取消 " name="B2">< /p>< /form>< A HREF="/asptest/shusheng/chat.asp"> 離開 < /a>< br>< br>< %If Request.Form("log")<>1 thenIf trim(Request.Form("talk"))="" then' 判斷用戶是否沒有輸入任何內容 talk=Session("nick")&" 沉默是金。"Elsetalk=trim(Request.Form("talk"))' 去掉字符后的空格 End IfApplication.lockApplication("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'> 來自 "&Request.ServerVariables("remote_addr")&" 的 "&Session("nick")&time&" 說:< /font>"&talk&"〈/td〉〈/tr〉< tr>< td width='100%' bgcolor='#C0C0C0'>〈/td〉〈/tr〉< /table>< br>"&Application("show")Application.UnLockResponse.Write Application("show")End IfEnd If%>
下面我們來對這個聊天室程序進行逐步的分析。
首先,由于聊天室的所有客戶都要能夠共享信息,所以不可避免的要用到具有應用程序級變量的對象 Application,這是建立 Chat 程序的關鍵所在,所有的談話數據都存放在一個應用程序級變量中,以便讓所有的客戶讀取。我們可以用所學過的 request 對象獲取客戶所輸入的談話,并保存在變量 talk 中 , 然后將 talk 的值存入應用程序級變量 show 中,如下 :
新聞熱點
疑難解答