This article mainly introduces the example of HTML5-WebSocket chat room implementation, which has certain reference value. Interested friends can refer to it.
The method of implementing a chat room on a traditional web page is to request the server to obtain relevant chat information at regular intervals. However, the websocket function brought by HTML5 has changed this method. Since websocket allows maintaining the connection for data interaction after connecting to the server, the server can actively send corresponding data to the client. For HTML5 processing, you only need to process the received data in the receive event of the websocket after the connection is created. Let's experience the function that the server can actively send to the client by implementing a chat room.
Function
A simple chat room mainly has the following functions:
1) Registration
Registration needs to handle several things, including obtaining a list of all users of the current server after the registration is completed, and the service sending the current successfully registered users to other online users.
2) Send a message
The server sends the currently received message to other online users
3)Exit
The server notifies other users of the disconnected user
The completed function preview of the chat room is as follows:
C# server code
The server-side code only needs to define a few 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); } } }
Only the above simple code is needed to complete the function of the chat room server. For user exit, the connection release event can be used 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-side code for chatting has been completed.
JavaScript code
The first thing to do for html5 code is to connect to the server. The relevant 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()); }
Use the Receive callback pool number to handle different messages. If the registration information of other users is received, the user information is added to the list; if the exit information of other users is received, the user information is added to the user list. Remove it; just receive the message directly and add it to the message display box. With the help of jquery, the above events become very simple.
User registration calling 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; } }); }
Getting online user list process:
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')); } }); }
Send Message process:
var callSay = { url: 'Handler.Say', parameters: {Content:""} } function Say() { callSay.parameters.Content = mEditor.html(); mEditor.html(''); channel.Send(callSay); $('#content1')[0].focus(); }
Code download: demo
Summary
The processing changes of websocket after code encapsulation It is very simple. If you are interested, you can extend this code to create a chat room with more functions, such as chat room grouping, sending information and picture sharing, etc.
The above is the detailed content of HTML5-WebSocket implementation chat room example. For more information, please follow other related articles on the PHP Chinese website!

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.