Home Web Front-end H5 Tutorial Implement websocket chat room using html5 websocket_html5 tutorial skills

Implement websocket chat room using html5 websocket_html5 tutorial skills

May 16, 2016 pm 03:48 PM

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('{<' 문서 .getElementById('name').value '> }');

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

복사 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('{ <' document.getElementById('name').value '>}');

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

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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

How to make pop-up windows with h5 How to make pop-up windows with h5 Apr 06, 2025 pm 12:12 PM

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

Is h5 same as HTML5? Is h5 same as HTML5? Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What application scenarios are suitable for H5 page production What application scenarios are suitable for H5 page production Apr 05, 2025 pm 11:36 PM

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5 Code: Accessibility and Semantic HTML H5 Code: Accessibility and Semantic HTML Apr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

See all articles