Home Web Front-end H5 Tutorial HTML5-WebSocket implementation chat room example

HTML5-WebSocket implementation chat room example

May 21, 2017 pm 03:10 PM
websocket chatroom

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);

            }
        }
    }
Copy after login

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);

            }

        }
Copy after login

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 = $(&#39;#nikename&#39;).val();

                channel.Send(callRegister, function (result) {

 

                    if (result.status == null || result.status == undefined) {

                        $(&#39;#dlgConnect&#39;).dialog(&#39;close&#39;);

                        registerid = result.data;

                        list();

                    }

                });

 

            };

            channel.Disposed = function (evt) {

                $(&#39;#dlgConnect&#39;).dialog(&#39;open&#39;);

            };

            channel.Error = function (evt) {

                alert(evt);

            };

            channel.Receive = function (result) {

                if (result.type == "register") {

                    var item = getUser(result.data);

                    $(item).appendTo($(&#39;#lstOnlines&#39;));

                }

                else if (result.type == &#39;unregister&#39;) {

                    $(&#39;#user_&#39; + result.data.ID).remove();

                }

                else if (result.type == &#39;say&#39;) {

                    addSayItem(result.data);

                }

                else {

                }

            }

            channel.Connect($(&#39;#host&#39;).val());

        }
Copy after login

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: &#39;Handler.Register&#39;, parameters: { name: &#39;&#39;} };

        function register() {

            $(&#39;#frmRegister&#39;).form(&#39;submit&#39;, {

                onSubmit: function () {

                    var isValid = $(this).form(&#39;validate&#39;);

                    if (isValid) {

                        connect();

                    }

                    return false;

                }

            });

        }
Copy after login

Getting online user list process:


var callList = { url: &#39;Handler.List&#39;, parameters: {} };

        function list() {

            channel.Send(callList, function (result) {

                $(&#39;#lstOnlines&#39;).html(&#39;&#39;);

                for (var i = 0; i < result.data.length; i++) {

                    var item = getUser(result.data[i]);

                    $(item).appendTo($(&#39;#lstOnlines&#39;));

                }

            });

        }
Copy after login

Send Message process:


var callSay = { url: &#39;Handler.Say&#39;, parameters: {Content:""} }

        function Say() {

            callSay.parameters.Content = mEditor.html();

            mEditor.html(&#39;&#39;);

            channel.Send(callSay);

            $(&#39;#content1&#39;)[0].focus();

        }
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use Java and WebSocket to implement real-time stock quotation push How to use Java and WebSocket to implement real-time stock quotation push Dec 17, 2023 pm 09:15 PM

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

See all articles