1. Overview
HTTP protocol is a stateless protocol. The server itself does not have the ability to identify the client and must rely on external mechanisms, such assession and cookie to maintain a conversation with a specific client. This brings some inconvenience, especially in situations where the server and client need to continuously exchange data (such as online chat). In order to solve this problem, HTML5 proposed the browser's WebSocket API.
The main function of WebSocket is to allow full-duplex communication between the server and the client. For example, the HTTP protocol is a bit like sending an email, and you have to wait for the other party to reply after sending it; WebSocket is like making a phone call, the server and the client can send data to each other at the same time, and there is a continuously open data channel between them.
The WebSocket protocol can completely replace the Ajax method and be used to send text and binary data to the server, and there is no "same domain restriction".
WebSocket does not use the HTTP protocol, but its own protocol. The WebSocket request issued by the browser is similar to the following:
GET / HTTP/1.1Connection: Upgrade Upgrade: websocket Host: example.com Origin: nullSec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ== Sec-WebSocket-Version: 13
The header information above shows that there is an HTTP header for Upgrade. The HTTP1.1 protocol stipulates that the Upgrade header information indicates switching the communication protocol from HTTP1.1 to the protocol specified by the item. "Connection: Upgrade" means that the browser notifies the server to upgrade to the webSocket protocol if possible. Origin is used to verify whether the browser domain name is within the server's permission range. Sec-WebSocket-Key is the key used for the handshake protocol, which is a base64-encoded 16-byte random string.
The server's WebSocket response is:
HTTP/1.1 101 Switching ProtocolsConnection: Upgrade Upgrade: websocket Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=Sec-WebSocket-Origin: nullSec-WebSocket-Location: ws://example.com
The server also uses "Connection: Upgrade" to notify the browser that the protocol needs to be changed. Sec-WebSocket-Accept means that the server adds the "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" string after the Sec-WebSocket-Key string provided by the browser, and then takes the hash## of sha-1. #value. The browser will verify this value to prove that it is indeed the target server that responded to the webSocket request. Sec-WebSocket-Location indicates the WebSocket URL of the communication.
Note: The WebSocket protocol is represented by ws. In addition, there is the wss protocol, which represents the encrypted WebSocket protocol and corresponds to the HTTPs protocol. After completing the handshake, the WebSocket protocol is on top of the TCP protocol and starts transmitting data. WebSocket protocol requires server support. Currently, the more popular implementation is socket.io based onnode.js. For more implementations, please refer to Wikipedia. As for the browser side, currently all mainstream browsers support the WebSocket protocol (including IE10+), the only exceptions are Opera Mini and Android Browser on the mobile phone.
2. ClientThe browser's processing of the WebSocket protocol is nothing more than three things:- Establishing a connection and disconnecting
- Sending data and receiving data
- Handling errors
attribute.
if (window.WebSocket != undefined) { // 支持}Then, start to establish a connection with the server (it is assumed that the server is the 1740 port of this machine and the ws protocol needs to be used).
if (window.WebSocket != undefined) { var connection = new WebSocket('ws://localhost:1740'); }
The WebSocket instance after establishing the connectionObject (that is, the connection in the above code) has a readyState attribute, indicating the current status, which can take 4 values:
- 0: Connecting
- 1: Connection successful
- 2: Closing
- 3: The connection is closed
event is triggered. At this time, you can send information to the server. We can specify the callback function of the open event.
connection.onopen = wsOpen;function wsOpen(event) { console.log('Connected'); }
Close WebSocket will trigger the close event.
connection.onclose = wsClose;function onClose(event) { var wasClean = event.wasClean; //bool值,连接是否关闭了 var code = event.code; //连接状态(数字),由服务端提供 var reason = event.reason; //关闭原因,由服务端提供 console.log('Closed'); } connection.close();
2.2 Sending and receiving data
After the connection is established, the client sends data to the server through the send method.connection.send(message);
In addition to sending strings, you can also use Blob or ArrayBuffer objects to send binary data.
//使用ArrayBuffer发送Canvas图像数据 var img = canvas_context.getImageData(0, 0, 400, 320); var binary = new Unit8Array(img.data.length);for(var i = 0; i < img.data.length; i++) { binary[i] = img.data[i] } connection.send(binary.buffer);//使用Blob发送文件 var file = document.querySelector('input[type="file"]').files[0]; connection.send(file);
客户端收到服务器发送的数据,会触发message事件。可以通过定义message事件的回调函数,来处理服务端返回的数据。
connection.onmessage = wsMessage; function wsMessage(event) { console.log(event.data); }
上面代码的回调函数wsMessage的参数为事件对象evnet,该对象的data属性包含了服务器返回的数据。
2.3 处理错误
如果出现错误,浏览器会触发WebSocket实例对象的error事件。
connection.onerror = wsError;function wsError(event) { console.log('Error: ' + event.data); }
3、服务器端
服务器端需要单独部署处理WebSocket的代码。下面用node.js搭建一个服务器环境。
var http = require('http');var server = http.createServer(function(request, response){});
假设监听1740端口。
server.listen(1740, function() { console.log((new Date()) + ' Server is listening on port 1740'); });
接着启动WebSocket服务器。这需要加载websocket库,如果没有安装,可以先使用命令安装。
var WebSocketServer = require('websocket').server;var wsServer = new WebSocketServer({ httpServer: server });
WebSocket服务器建立request事件的回调函数。
var connection; wsServer.on('request', function(req){ connect = req.accept('echo-protocol', req.origin); });
上面代码的回调函数接受一个参数req,表示request请求对象。然后,在回调函数内部,建立WebSocket连接Connection。接着,就要对connection的message事件指定回调函数。
wsServer.on('request', function(r) { connection = req.accept('echo-protocol', req.origin); connection.on('message', function(message) { var msgString = message.utf8Data; connection.sendUTF(msgString); }); });
最后,监听用户的disconnect事件。
connection.on('close', function(reasonCode, description) { console.log(connection.remoteAddress + ' disconnected'); });
4、Socket.io简介
Socket.io是目前最流行的WebSocket实现,包括服务器和浏览器两个部分。它不仅简化了接口,使得操作更容易,而且对于那些不支持WebSocket的浏览器,会自动降为Ajax连接,最大限度地保证了兼容性。
第一步,在服务器端的项目根目录下,安装socket.io模块。
npm install socket.io
第二步,在根目录下建立app.js,并写入以下代码(使定使用了Express框架)。
var app = require('express')(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); server.listen(80); app.get('/', function (req, res) { res.sendfile(dirname + '/index.html'); });
上面代码表示,先建立并运行HTTP服务器。Socket.io的运行建立在HTTP服务器之上。
第三步,将Socket.io插入客户端网页。
<script src="/socket.io/socket.io.js"></script>
然后,在客户端脚本中,建立WebSocket连接。
var socket = io.connect('http://localhost');
由于本例假定WebSocket主机与客户端是同一台机器,所以connect方法的参数是http://localhost。接着,指定news事件(即服务器端发送news)的回调函数。
socket.on('news', function (data){ console.log(data); });
最后,用emit方法向服务器端发送信号,触发服务器端的anotherNews事件。
请注意:emit方法可以取代Ajax请求,而on方法指定的回调函数,也等同于Ajax的回调函数。
第四步,在服务器端的app.js中加入以下代码。
io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('anotherNews', function (data) { console.log(data); }); });
上面代码的io.sockets.on方法指定connect事件(WebSocket连接建立)的回调函数。在回调函数中,用emit方法向客户端发送数据,触发客户端的news事件。然后,再用on方法指定服务器端anotherNews事件的回调函数。
The above is the detailed content of HTML5 new features WebSocket. For more information, please follow other related articles on the PHP Chinese website!

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

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.


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

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

SublimeText3 Chinese version
Chinese version, very easy to use

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