ASP.NET 开发聊天室程序(英文)

转载 2008年05月01日 02:49:00
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src=""> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src=""> </script>
In its new avatar, ASP has undergone a metamorphosis. It is no longer confined to simple server-side scripting. It is no more mere bits of HTML contents or data inserted into template HTML code. With it, you can create a full-fledged web application, on the fly, with control over several critical factors.

Anyway, you may ask, what is the difference between a web application and a web page? In server side scripting your role is limited to, and ends with, the rendering of the web page on the client's browser, save that, you can maintain some control over the session and session related variables. On the other hand, for a web application, you approach the whole affair differently - the server is where the action takes place and the page is no longer a simple HTML document. Instead, the web page is a frame on which you create an interactive session between you and the client or between clients among themselves. You compose it from scratch placing elements at the appropriate places, wiring up event handling, storing variables not only for the session state but also for the application state and most importantly controlling flow of information between client and server and from client to client.

The last mentioned ability makes an ASP.NET application into a Peer 2 Peer NETworked Application. This article will present you with one such Peer 2 Peer NETworked application in the form of a Chat application.

Charting the course for chatting
How do you create a Chat Application? Traditionally, for a chat application, you have to create aserver side listener, which requires a server side TCP/IP channel and listens for requests from clients. These requests can be of two types:

Registering a new chat participant
Passing on chat messages to other chat participants.
In addition, the server-side program gets a handle to the client object and uses this handle to update chat messages of the participants as well as the list of participants at any given time.

However, in this ASP.NET application, the problem of the Server-side listener can be side stepped, as ASP.NET itself will be the listener. Thus there is no hogging of a TCP/IP channel for a dedicated listener.Since an ASP.NET Application uses the HTTP Protocol and the corresponding Port 80, it is not affected by most of the firewalls, unlike a dedicated chat listener. TheHttpApplicationState State Object, provided to us by the NET Framework, solves the problem of sharing information across applications. The options available to us in this regard are:

TheHttpApplicationState Object,
The System.Web.Caching.Cache object,
Database back end
The Isolated Storage Dump.
Whilst the last two options involve Read/Write/IO operations, they are not suitable for a simple chat application where the speed is the essence and there is no great amount of memory involved. The cache object does not provide for locking and may affect synchronization when several users access the page at the same time. Hence, we zero in on theHttpApplicationState object for our data storage. Finally we handle the trickiest question of pushing messages from the server to the client using the web services behavior of InterNET Explorer 5.0 and above

There is also no need for support staff starting or ending an application.ASP.NET acts as the master application and is expected to keep going as long as the IIS is running on the Server.

Thus, we can summarize our course of action as follows:

Design aChatMessage Object and create a placeholder for these objects at the Application Level. (Why do we do this at the Application' Level? - ASP.NET enables us to keep variables at the Application level as well as at the Session level. However, the session level variables cannot be shared between sessions unlike the Application level variables. Therefore, we pitch for the Application variables.)
Create a web service which provides three methods - one for registering a participant, one for exchanging messages with him and one for merely supplying the waiting messages at the askance!
Design a client web page that uses DHTML Behavior known as webservice behavior given to us by Microsoft as
Componentise the client side code - so that web developers need not know the intricacies of using Web Services, XML, XMLHttp and DHTML Behaviors, in order to use the application we made.
Creating the webservice:
As mentioned earlier, in a Peer to Peer application, the server support is needed for three actions - registering the peers, receiving messages for routing and passing on waiting messages. Therefore, our web service will have three Web Methods:

public string RegisterMember(String NickName)
public ChatMessage XchangeMsgs(String NickName, String Msg)
public ChatMessage GetMsgs(String NickName)
The web service is encapsulated in a class called ChatWebService, which is derived from System.Web.Servicesand is contained in the source code fileChatWebService.cs in the namespace PrasadWeb. The namespace also defines two other classes calledMember and ChatMessage. The classMessage has a string variable called UserName, a DateTime variable calledLastAccessTime and a public property NickName, which gets and sets the variableUserName together with the time of his registration. The ClassChatMessage has merely two string variables calledUserList and Messages. These two variables hold formatted lists of Chat Participants and the undelivered chat messages at any given time.

The main classChatWebService has two private methodsString GetMemberList() and Void CheckMemberList(), besides the three Web Methods mentioned earlier. The former function returns the list of chat participants at any given time as a formatted list. The later function checks to see if any chat client has been absent from the circuit for more than 2 minutes and removes him from the chat list, so as to keep the environment free from quitters. TheGetMemberList function works as follows:

public String GetMembersList()
 {
// We need to lock the app to enable syncronization
// The variable for the return message
String UserList = "";

// Every web application has an Application property
// which yields a handle to the ApplicationState object.
// ApplicationState object stores the collection of
// Member Objects (we will see latter how we do it).
// We obtain an array of the Keys to the collection
// and store the array in a variable 'Members'
String[] Members = Application.AllKeys;

// We can now unlock the application
// Now we read the UserName variable in each Member
// object found in the HttpApplicationState State Collection
// and store these values in a string separated by
// NewLine Characters

for (int x=0;x

As the application involves multiple users - all accessing the same set of variables stored by us in the application object - we need to use Code Synchronization by invoking theLock andUnLock methods of theSystem.Web.HttpApplicationState State object whenever a write operation is performed by us.

In theRegisterMember method, we first check if the username supplied by the client is unique - if not, reject the name. Then, we instantiate a newMember object for the new participant and add the object to theApplicationState objects collection. We do these with the following code:

public string RegisterMember(String NickName)
 CheckMembersList();
 String[] Members = Application.AllKeys;
 If ((Members.Length>0)&&(Array.IndexOf(Members,NickName)>-1))
 {
throw new Exception("UserName Already Exists.
Please Select another name");
 }
 Member NewMember = new Member(NickName);
 Application.Lock();
 Application.Add(NickName, NewMember);
 Application.UnLock();
 return GetMembersList();

Again, all these are done in alocked state.

Whenever a client sends a message through theXchangeMsgs method, we first call theCheckMembers private method to update the list of chat participants in our collection. Then we check if the just received message carries a familiar Nick Name that is already registered with us. Then we loop through all theMember objects in our collection, open each of them and insert the just received message into theMessages variable of each of theseMember objects - after due HTML Formatting. Finally, we retrieve theMessages string stored in theMember object corresponding to the current client caller as the return value and empty theMessages variable of that object.

TheGetMsgs web method is similar to the above except that this method does not being us any new messages from the client and it is merely called to collect all the pending messages and the current list of chat participants.

Creating the Chat Client:
Our Chat Client is an HTML Web Page, which contains a table with 7 rows and one column. The first row contains the name of the Chat Application. The even numbered rows bear the captions and row number three contains the Chat Participants List whilst row five is for chat messages. The last row has a Text Box and a Submit button. Rows three and five house aelement within them, whosescroll property has been set toauto.

Attaching the WebService Behavior:
The table webservice behavior defined in the file, as follows:

 id="service"
 onresult="service_onmyresult();"
 onready=" = 'visible';'none';"
 border="0"
 style=
 "Background-Color:
 White;Height:60%;
 Border-Bottom:#A03399 solid 2px;
 ForeColor:Black;
 width:45%;
 Behavior:url('http://localhost/dotNET/chatroom/');
 Border-Left:#99ccff solid 2px;
 Border-Right:#A03399 solid 2px;
 Position:Relative;
 Visibility:hidden;
 Width:30%;
 Border-Top:#99ccff solid 2px;
 Table-Layout:Fixed;
 Border-Style:#008080 solid 2px;">

The page has two script blocks of which one is invoked on theonLoad event of the window. This script block calls the use method of the webservice behavior by passing the URI of the webservice as a parameter as follows:

The other parameter supplied to the method is the name of the service ChatServe. The second code block initializes three variables called iCallID1,iCallID2 and iCallID3, to store the ID of the three web method calls. It also initializes anXMLDom ActiveX Object called Msg_XML, to enable us to store the SOAP messages returned by the web service.

When the user types his nick name in the Text Box and presses the submit button, an asynchronous call is made to the Web Service'sRegisterMember method, by invoking thecall method found in the The method formats the SOAP request for theWeb Method, sends it to the web service host server using theXMLHttp object of theMSXML ActiveX object and returns the initializer for theiCallID1 variable. The DHTML Behavior ensures that when the webservice returns a SOAP Message from the server, anonResult event is fired upon the Table. The event handler for this event first checks up if the return value is an error message and if not, whether the return message is for the iCallID1. On passing these tests, the XML value of the result is stored in theXMLDom object called Msg_XML.

At this stage the XML returned by the server will resemble the following:


The Chat List in the return message, which isPrasad Uriah Charlotte is parsed out by applying the XPath pattern//UserList on the XML String and written into the table as the inner HTML of the Chat List panel as follows:

service_ChatList.innerText = service_MsgXML.selectSingleNode("//UserList").text;

The method then goes on to set a timer to invoke theGetMsgs method of the web service after 3 seconds. The return value of this method is parsed and placed as the inner HTML of the Chat List panel and the Chat Messages panel of the Table. This method sets up a timer to call itself once every 3 seconds.

Whenever the client types a message in the text box and presses the submit button, theXchangeMsgs method of the web service is invoked by the DHTML Behavior component. The return value of this method being similar to the one described above, is dealt with in the same manner.

This, in brief, is the designing of the client object. You will need to take a deeper look into theClientSide.html file given in the code download for this article to read the intricate details of the client side coding involved.

Making a control for the client side:
All that was described in the preceding section was the HTML code required to be supplied to the client browser. However, since ASP.NET is based on components, we need to make it easy for the web developer by encapsulating all these HTML code into a Control. Therefore, let us go on to create the ASP.NET custom control called TestWebControl. (See the code listing in the file TestWebControl.cs).

This control is derived from theSystem.Web.UI.WebControls.table object of the Framework. In it we override the protected method ofInit() and define various style elements for our component with the objective that the web developer using this control will have total say on how the control looks.

The properties we add to the control include oneBehaviorURI and one ServiceURI, which enable the control user to specify the URL of the file on the server and the URI of the webservice. We, then, go on to instantiate new TableCell elements from the Framework, setting them with all the variables containing the css properties and finally adding them to our control - which is a sub class of the Table class. For this, we must first add the Table Cell into a newly instantiated TableRow element through its Cells Collection and the table row should be added to the Rows Collection of our control. Then, the client side scripts are all written into a string variable called Doc. An easy way of adding any script to the output document is to use theWrite Method of theHtmlTextWriter Object given to us when we override theRender Method. Therefore, to do the writing, we store the entire script block in thisDoc variable.

Finally we override the Render method of the Table class and write the scripts on to the client browser using theHtmlTextWriter object handed over to us by this method. We should not forget to call the base class'sRender Method, lest all our initialization code is left out of the page.

The Control thus created is used in any ASP.NET web form by inserting the following code: (You may change the URIs according to your server settings)

When running this application you will see a screen such as below that you can log on to and interact on.If you get someone else to log on to the page on to their computer you can have a conversation:

In this article we saw how to create a chat application using ASP.NET.Hopefully through this you will see the benefits of using ASP.NET for this sort of application and how by doing this you can avoid issues such as creating a server side listener.In this application you cannot log off yourself, but you can change the timing that people are logged on and inactive before being disconnected for longer than two minutes in the C sharp code.This article should help you develop your own ASP.NET chat applications.

[download relative material]
seover="window.status='正文--ASP.NET 开发聊天室程序(英文)';return true">
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 728x15, 创建于 08-4-23MSDN */ google_ad_slot = "3624277373"; google_ad_width = 728; google_ad_height = 15; //--> </script> <script type="text/javascript" src=""> </script>
<script type="text/javascript"><!-- google_ad_client = "pub-2947489232296736"; /* 160x600, 创建于 08-4-23MSDN */ google_ad_slot = "4367022601"; google_ad_width = 160; google_ad_height = 600; //--> </script><script type="text/javascript" src=""> </script>

ASP.NET 开发聊天室程序(英文)

Introduction:In its new avatar, ASP has undergone a metamorphosis. It is no longer confined to simpl...
  • zdg
  • zdg
  • 2001年04月11日 12:18
  • 3924


登录界面如图: ——logi
  • yayun0516
  • yayun0516
  • 2014年11月05日 08:57
  • 1781


  • lj_2_0_2
  • lj_2_0_2
  • 2015年11月01日 14:36
  • 3306


  • aspnet2002web
  • aspnet2002web
  • 2011年03月17日 23:42
  • 8942


用ASP.NET做一个最简单的聊天室,逻辑清晰简单,能帮你了解Application的用法。 第一步我们先构想我们需要的页面,应该也就是两个吧,第一个登陆页面Login.aspx,第二个聊天室主页面...
  • u011955860
  • u011955860
  • 2013年12月27日 10:01
  • 2971


wechat-chat 本项目使用 Gorilla WebSocket 作为聊天室后台 , Gorilla WebSocket 基于go语言开发,提供的demo实例中有聊天室源码,不需要任何修改...
  • han_cui
  • han_cui
  • 2017年01月14日 11:33
  • 1437 MVC4 + signalR 聊天室实现 MVC4 + signalR 聊天室实现
  • csharp25
  • csharp25
  • 2015年06月13日 10:35
  • 2230

JAVA 的聊天室程序

终于完成了这个实验了,写了报告以及 email 给老师了。一直很懒,不过这个程序写得还挺顺利的,用 JAVA 进行网络编程和多线程编程很方便,只是界面编程比较麻烦点,不过为了省事我的界面做得挺简洁的。...
  • Rappy
  • Rappy
  • 2007年11月15日 15:49
  • 7709


 介绍我的第一个简单的Chat room 是用ASP 3.0 写成的。那无外乎有二个TextBox,他们发送消息给程序变量然后显示在一个每秒刷新的页面上。在那个时代,一个真正的聊天室必须运用Java ...
  • moremoreTea1983
  • moremoreTea1983
  • 2007年06月13日 23:27
  • 1528

即时通讯 音视频聊天室开发建议

目前网上视频聊天室、视频会议软件、可视IP电话软件随处可见,你是否想自己做一个玩玩?其实这类软件无非是视频加上网络而建成的。如果熟悉视频捕 捉和网络传输技术,根本就难不倒你。本文详细介绍了如何利用别人...
  • little_rui
  • little_rui
  • 2015年02月11日 13:56
  • 603
您举报文章:ASP.NET 开发聊天室程序(英文)