Introduction to websocket and other reverse ajax technologies
In real-time web applications, a common method is reverse Ajax. Definition of reverse Ajax:
Reverse Ajax (Reverse Ajax) is essentially a concept that can send data from the server to the client. In a standard HTTP Ajax request, data is sent to the server. Reverse Ajax can simulate an Ajax request in some specific ways. These methods will be discussed in this article. In this way, the server can send data to the server as quickly as possible. Client sends events (low latency communication).
Reverse Ajax technology mainly has two contents: one is that the server maintains the TCP connection until it has data to send to the client (can be implemented using loops and sleep), and the other is client js programming skills.
Websocket is a standard of HTML5 and is also an anti-ajax technology.
Socket.io implementation of reverse AJAX technology example
socket.io official introduction:
Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript. In order to provide realtime connectivity on every browser, Socket. IO selects the most capable transport at runtime, without it affecting the API. WebSocket Adobe® Flash® Socket AJAX long polling AJAX multipart streaming Forever Iframe JSONP Polling
Simply speaking, socket.io is a library based on nodejs, which packages multiple reverse ajax technologies and unifies the interface. At runtime, socket.io automatically selects the appropriate reverse ajax technology to interact with the socket.io server based on the browser's conditions. If technologies such as websocket are standards, then socket.io is an application.
Here’s how to install it (the author uses Linux Mint 16):
Install node.js:
Install npm:
socket.io example
The following examples are from the official website and have been modified appropriately.
First create the server-side (server-side) code (file test.js):
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event' , function (data) {
console.log(data);
});
});
The author built an nginx server, which uses port 80 and the web root directory is /usr/share/nginx/html. Copy socket.io.min.js under ~/node_modules/socket.io/node_modules/socket.io-client/dist to the web root directory, and create the file index.php in the web root directory (as a client) , the content is as follows: