Use Ajax and ASP.net to implement simple chat rooms

Source: Internet
Author: User
Tags implement net return variable

  introduce

My first simple chat room was written in ASP 3.0. There are two textbox, they send a message to the program variable and then appear on a page refreshed every second. In those days, a real chat room had to use Java applets or ActiveX control. But it all changed after the advent of Ajax. Ajax is an asynchronous communication mechanism that combines XML and JavaScript. Now we can just use server code and a little JavaScript. This article is about how to use AJAX technology to build a simple chat room.

  Sample Programs

The sample program is a single multi-user chat room. It maintains a list of logged-in users internally. The list will eliminate users who have expired session. It also supports commands such as/admin clear purge chat room/nick [name] To change the user's name.

  you also need to know

This program uses a class called Chatengine. This class controls all users and messages. Users are stored in a Hashtable, and messages are stored in StringCollection:

Hashtable users; StringCollection chat;
A Chatengine global instance is placed in the Global.asax.cs:

public static UChat.ChatEngine.IChatEngine Engine =new UChat.ChatEngine.ChatEngine ();
A JavaScript function is used asynchronously to display data from a global variable on the page:

function Settimers () {Timeid = Window.settimeout ("UpdateAll ()", refreshrate);}
Use each user-supplied name and ID to identify the user:

public void AddUser (string id, string user) {//make sure user name does not exist Alreadyif (! UserExists (user)) {//add user to users listusers. ADD (ID, user);//display a notification message to all users chat. ADD (this. Makeservermessage (String. Format (joinedfmt, user));}

  screenshots and implementation steps

The home page shows the basic information of the chat room, such as how many people are in the chat room, the size of the chatlog.

In order to be able to log in to the chat room, a name must be provided.

When the Login button is clicked. The following code is executed:

protected void Login (object sender, EventArgs e) {String user = Txtusername.text;if (! Validatenick (user)) Return;if (Global.Engine.UserExists (user)) {lblerrormsg.text = "A user with this" + "name already exists, try again. " return;} Response.Redirect ("server.aspx?action=login&u=" + user);}

After some validation, the user is moved to another page that uses the AddUser function to put the user in the user list. When it's all done. The user will then be directed to the Chat.aspx page, and the following JavaScript function will be executed on this page:

<script type= "Text/javascript" >sniffbrowsertype ()//shows loading. Screenshowloadscreen ();//set the JavaScript timer and//loads user list and Messages Settimers (); SetFocus (' MyText ');< /script><input type= "text" class= "MyText" id= "MyText" >

When the user enters the text and presses the carriage return. The following code is executed:

Capture the ENTER key on the input box and post Messagefunction Capturereturn (event) {if (Event.which | | event.keycode) {if (Event.which = 13) | | (Event.keycode = 13)) {PostText (); return false;} else {return true;}}} function PostText () {rnd++;//clear text box Firstchatbox = getelement ("mytext"); chat = Chatbox.value;chatbox.value = ""/ Get user GUID from urluserid = location.search.substring (1, location.search.length);//construct Ajax Server urlurl = ' Se Rver.aspx?action=postmsg&u= ' + userid + ' &t= ' +encodeuricomponent (chat) + ' &session= ' + rnd;//create and set T He instance//of appropriate XMLHTTP Request objectreq = Getajax ();//update page with new Messagereq.onreadystatechange = function () {if (req.readystate = 4 && Req.status = =) {UpdateAll ();}} Req.open (' Get ', url, true); Req.send (null);}

Completed! This is it. Nothing special, download the sample program, and then understand the code!



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.