search
HomeWeb Front-endH5 TutorialImplement websocket chat room using html5 websocket_html5 tutorial skills

What is websocket

The WebSocket protocol is a new protocol introduced by html5. Its purpose is to achieve full-duplex communication between the browser and the server. Students who read the link above must have already understood how to do this in the past with low efficiency and high consumption (polling or comet). In the websocket API, the browser and server only need to perform a handshake action, and then, A fast channel is formed between the browser and the server. Data can be transmitted directly between the two. Doing this at the same time has two benefits

1. Reduced communication transmission bytes: Compared with the previous use of http to transmit data, websocket transmits very little additional information. According to Baidu, it is only 2k

2. The server can actively push messages to the client without the client having to query

The concepts and benefits are everywhere on the Internet, so I won’t go into details. Let’s take a brief look at the principles and then start writing a web version of the chat room.

Shake hands

In addition to the three-way handshake of the TCP connection, in the websocket protocol, the client and the server need an additional handshake to establish a connection. In the latest version of the protocol, it looks like this

The client sends a request to the server Send request


Copy code
The code is as follows:

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8080
Origin: http:/ /test.com
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: OtZtd55qBhJF2XLNDRgUMg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36

The server responds

Copy the code
The code is as follows:

HTTP/ 1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: xsOSgr30aKL2GNZKNHKmeT1qYjA=

The "Sec-WebSocket-Key" in the request is random , the server will use these data to construct a SHA-1 information digest. Add the magic string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to "Sec-WebSocket-Key". Use SHA-1 encryption, then BASE-64 encoding, and return the result to the client as the value of the "Sec-WebSocket-Accept" header (from Wikipedia).

websocket API

After the handshake, the browser and the server establish a connection, and the two can communicate with each other. The API of websocket is really simple. Take a look at the W3C definition


Copy the code
The code is as follows:

enum BinaryType { "blob", "arraybuffer" };
[Constructor(DOMString url, optional (DOMString or DOMString[]) protocols)]
interface WebSocket : EventTarget {
readonly attribute DOMString url;

// ready state
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSING = 2;
const unsigned short CLOSED = 3;
readonly attribute unsigned short readyState;
readonly attribute unsigned long bufferedAmount;

// networking
attribute EventHandler onopen;
attribute EventHandler onerror;
attribute EventHandler onclose;
readonly attribute DOMString extensions;
readonly attribute DOMString protocol;
void close([Clamp] optional unsigned short code, optional DOMString reason);

// messaging
attribute EventHandler onmessage;
attribute BinaryType binaryType;
void send(DOMString data);
void send(Blob data);
void send(ArrayBuffer data);
void send(ArrayBufferView data);
};

Create websocket

Copy code
The code is as follows:

ws=new WebSocket(address); //ws://127.0.0.1:8080


Call its constructor and pass in the address to create A websocket, it is worth noting that the address protocol must be ws/wss

Close socket

Copy code
The code is as follows:

ws.close();


웹 서비스를 닫으려면 웹 서비스 인스턴스의 close() 메서드를 호출하세요. 물론 웹 서비스가 닫힌 이유를 설명하는 코드와 문자열을 전달할 수도 있습니다.

여러 콜백 함수 핸들

비동기 실행으로 인해 콜백 함수는 당연히 필수입니다.

onopen: 연결이 생성된 후 호출됩니다.
onmessage: 서버 메시지를 받은 후 호출됩니다. .
onerror: 오류가 발생할 때 호출됩니다.
onclose: 연결을 닫을 때 호출됩니다.

이름을 보면 그 기능을 알 수 있습니다. 각 콜백 함수는 Event 개체를 전달하며 메시지는 event.data를 통해 액세스할 수 있습니다.

API 사용

소켓을 성공적으로 생성한 다음 콜백 함수에 값을 할당할 수 있습니다


코드 복사
코드는 다음과 같습니다. 다음과 같습니다:

ws=new WebSocket(address);
ws.onopen=function(e){
var msg=document.createElement('div');
msg.style.color='#0f0';
msg.innerHTML="서버 > 연결이 열려 있습니다.";
msgContainer.appendChild(msg);
ws.send('{ }');

이벤트 바인딩을 사용할 수도 있습니다.

복사 code
코드는 다음과 같습니다:

ws=new WebSocket(address);
ws.addEventListener('open',function(e){
var msg=document.createElement('div') ;
msg.style.color='#0f0';
msg.innerHTML="서버 > 연결이 열려 있습니다.";
msgContainer.appendChild (msg);
ws.send('{ }');

클라이언트 측 구현
사실 클라이언트 측 구현은 웹소켓과 관련된 몇몇 문장을 제외하면 비교적 간단합니다. 자동 포커스, 키 입력 이벤트 처리, 자동 위치 지정 등 몇 가지 간단한 기능이 있습니다. 메시지박스는 하단에 하나씩 설명하지 않겠습니다

Statement
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
How to Add Audio to My HTML5 Website?How to Add Audio to My HTML5 Website?Mar 10, 2025 pm 03:01 PM

This article explains how to embed audio in HTML5 using the <audio> element, including best practices for format selection (MP3, Ogg Vorbis), file optimization, and JavaScript control for playback. It emphasizes using multiple audio f

How to Use HTML5 Forms for User Input?How to Use HTML5 Forms for User Input?Mar 10, 2025 pm 02:59 PM

This article explains how to create and validate HTML5 forms. It details the <form> element, input types (text, email, number, etc.), and attributes (required, pattern, min, max). The advantages of HTML5 forms over older methods, incl

How do I use the HTML5 Page Visibility API to detect when a page is visible?How do I use the HTML5 Page Visibility API to detect when a page is visible?Mar 13, 2025 pm 07:51 PM

The article discusses using the HTML5 Page Visibility API to detect page visibility, improve user experience, and optimize resource usage. Key aspects include pausing media, reducing CPU load, and managing analytics based on visibility changes.

How do I use viewport meta tags to control page scaling on mobile devices?How do I use viewport meta tags to control page scaling on mobile devices?Mar 13, 2025 pm 08:00 PM

The article discusses using viewport meta tags to control page scaling on mobile devices, focusing on settings like width and initial-scale for optimal responsiveness and performance.Character count: 159

How do I handle user location privacy and permissions with the Geolocation API?How do I handle user location privacy and permissions with the Geolocation API?Mar 18, 2025 pm 02:16 PM

The article discusses managing user location privacy and permissions using the Geolocation API, emphasizing best practices for requesting permissions, ensuring data security, and complying with privacy laws.

How to Create Interactive Games with HTML5 and JavaScript?How to Create Interactive Games with HTML5 and JavaScript?Mar 10, 2025 pm 06:34 PM

This article details creating interactive HTML5 games using JavaScript. It covers game design, HTML structure, CSS styling, JavaScript logic (including event handling and animation), and audio integration. Essential JavaScript libraries (Phaser, Pi

How do I use the HTML5 Drag and Drop API for interactive user interfaces?How do I use the HTML5 Drag and Drop API for interactive user interfaces?Mar 18, 2025 pm 02:17 PM

The article explains how to use the HTML5 Drag and Drop API to create interactive user interfaces, detailing steps to make elements draggable, handle key events, and enhance user experience with custom feedback. It also discusses common pitfalls to a

How do I use the HTML5 WebSockets API for bidirectional communication between client and server?How do I use the HTML5 WebSockets API for bidirectional communication between client and server?Mar 12, 2025 pm 03:20 PM

This article explains the HTML5 WebSockets API for real-time, bidirectional client-server communication. It details client-side (JavaScript) and server-side (Python/Flask) implementations, addressing challenges like scalability, state management, an

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

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