The traditional way to implement chat rooms on Web pages is to request the server to obtain related chat information at intervals. However, the websocket function brought about by html5. because websocket allows a connection to the server for data interaction, the server can actively send data to the client. for HTML5 processing, you only need to process the received data in the receive event of websocket after the connection is created. the following uses a chat room to experience the functions that the server can actively send to the client.
Function
A simple chat room provides the following functions:
1) Registration
Registration involves obtaining the list of all users on the current server after registration. The Service sends successfully registered users to other online users.
2) send messages
The server sends the received message to other online users.
3) quit
The server notifies other users of the disconnection.
The following is a preview of the functions completed in the chat room:
C # Server Code
you only need to define several methods for the server code, namely, registration, obtaining other users and sending information. the Code is as follows:
/// <Summary> // copyright henryfan 2012 // Email: henryfan@msn.com // homepage: http://www.ikende.com // createtime: 21:45:25 // </Summary> class handler {public long register (string name) {tcpchannel channel = methodcontext. current. channel; console. writeline ("{0} register name: {1}", channel. endpoint, name); channel. name = Name; jsonmessage MSG = new jsonmessage (); User user = new user (); User. name = Name; user. id = channel. clientid; user. IP = channel. endpoint. tostring (); channel. tag = user; MSG. type = "register"; MSG. data = user; foreach (tcpchannel item in channel. server. getonlines () {If (item! = Channel) item. send (MSG);} return channel. clientid;} public ilist <user> List () {tcpchannel channel = methodcontext. current. channel; ilist <user> result = new list <user> (); foreach (tcpchannel item in channel. server. getonlines () {If (item! = Channel) result. add (User) item. tag);} return result;} public void say (string content) {tcpchannel channel = methodcontext. current. channel; jsonmessage MSG = new jsonmessage (); saytext ST = new saytext (); ST. name = channel. name; ST. id = channel. clientid; ST. date = datetime. now; ST. content = content; ST. IP = channel. endpoint. tostring (); MSG. type = "say"; MSG. data = sT; foreach (tcpchannel item in channel. server. getonlines () {item. send (MSG );}}}
You only need the simple code above to complete the functions of the chat room server. You can use the connection release event to exit the user to handle the specific code:
Protected override void ondisposed (Object sender, channeldisposedeventargs e) {base. ondisposed (sender, e); console. writeline ("{0} disposed", E. channel. endpoint); jsonmessage MSG = new jsonmessage (); User user = new user (); User. name = E. channel. name; user. id = E. channel. clientid; user. IP = E. channel. endpoint. tostring (); MSG. type = "unregister"; MSG. data = (User) E. channel. tag; foreach (tcpchannel I TEM in this. server. getonlines () {If (item! = E. Channel) item. Send (MSG );}}
In this way, the server code of the chat is complete.
JavaScript code
The first thing to do with HTML5 code is to connect to the server. The related JavaScript code is as follows:
Function connect () {channel = new tcpchannel (); channel. connected = function (EVT) {callregister. parameters. name = $ ('# nikename '). val (); channel. send (callregister, function (result) {If (result. status = NULL | result. status = undefined) {$ ('# dlgconnect '). dialog ('close'); registerid = result. data; List () ;}}) ;}; channel. disposed = function (EVT) {$ ('# dlgconnect '). dialog ('open') ;}; channel. error = function (EVT) {alert (EVT) ;}; channel. receive = function (result) {If (result. type = "register") {var item = getuser (result. data); $ (item ). appendto ($ ('# lstonlines');} else if (result. type = 'unregister ') {$ (' # user _ '+ result. data. ID ). remove ();} else if (result. type = 'say') {addsayitem (result. data);} else {} channel. connect ($ ('# host '). val ());}
The number of receive callback pools is used to process different messages. If the registration information of other users is received, the user information is added to the list; if you receive exit information from other users, you can remove it from the user list. You can directly receive the message and add it to the message display box. with the help of jquery, the above events have become very simple.
User Registration call process:
VaR callregister = {URL: 'handler. register ', parameters: {Name: ''}; function register () {$ (' # frmregister '). form ('submit ', {onsubmit: function () {var isvalid = $ (this ). form ('validate'); If (isvalid) {connect () ;}return false ;}});}
Process of obtaining the online user list:
VaR calllist = {URL: 'handler. list', parameters :{}; function list () {channel. send (calllist, function (result) {response ('{lstonlines'{.html (''); For (VAR I = 0; I <result. data. length; I ++) {var item = getuser (result. data [I]); $ (item ). appendto ($ ('# lstonlines '));}});}
Message sending process:
VaR callsay = {URL: 'handler. say ', parameters: {content: ""} function say () {callsay. parameters. content = meditor.html (); meditor.html (''); channel. send (callsay); $ ('# content1') [0]. focus ();}
Summary
After code encapsulation, websocket processing becomes very simple. If you are interested, you can expand a chat room with more functions, such as chat room grouping and sending information and Image Sharing.
Download Code: chatroom.rar (1.09 MB)
Demo address: http://html5.ikende.com/chatroom.htm