HTML5-WebSocket to achieve chat room example, websocket to achieve chat room
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
The server-side code only needs to define several methods for several functions, namely registration, obtaining other users and sending information. The specific code is as follows:
/// <summary> /// Copyright © henryfan 2012 ///Email: henryfan@msn.com ///HomePage: http://www.ikende.com ///CreateTime: 2012/12/7 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 item 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) { $('#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(); }
Download Code: demo
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.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.