WebSocket Simple Introduction

Source: Internet
Author: User

Today talk about timely communication, suddenly be asked to push the way, or timed to accept the way, because the previous pages are used in the traditional AJAX processing, may be the timing of Ajax is deeply rooted, so there is no same how the same how will appear to push the way?
The thread was suddenly caught in the head when it was mentioned websocket.
First, WebSocket is HTML5 out of the Thing (protocol), that is, the HTTP protocol does not change, or it is OK, but HTTP is not support for persistent connection (long connection, not counting the loop connection)
First of all, HTTP has 1.1 and 1.0 say, that is called keep-alive, to merge multiple HTTP requests into one, but WebSocket is actually a new protocol, with the HTTP protocol basically does not matter, just to be compatible with the existing browser handshake specification, that is, Websockt and HTTP have Set, but not all.
Another HTML5 refers to a series of new APIs, or new specifications, and new technologies. The HTTP protocol itself is only 1.0 and 1.1, and is not directly related to HTML itself. In layman's terms, you can transfer non-HTML data using the HTTP protocol. = is something at different levels.

Second, the characteristics of WebSocket
The most important thing to write before other features is that you can push messages from the server to the client.
(1) based on the TCP protocol, the server-side implementation is relatively easy.
(2) Good compatibility with HTTP protocol. The default port is also 80 and 443, and the handshake phase uses the HTTP protocol, so the handshake is not easy to block, through a variety of HTTP proxy server.
(3) The data format is lighter, the performance overhead is small, and the communication is efficient.
(4) You can send text, or you can send binary data.
(5) The client can communicate with any server without the same origin limitation.
(6) The protocol identifier is WS (or WSS if encrypted) and the server URL is the URL.

Third, WebSocket Simple API
1. Constructors
The WebSocket object is used as a constructor for creating a new WebSocket instance.
var ws = new WebSocket (' ws://localhost:8080 ');
After executing the above statement, the client connects to the server.
2. Status return
The ReadyState property returns the current state of the instance object, in total four.
Connecting: A value of 0 indicates that the connection is in progress.
OPEN: A value of 1 means that the connection is successful and communication is possible.
CLOSING: A value of 2 indicates that the connection is shutting down.
CLOSED: A value of 3 indicates that the connection has been closed or the connection failed to open.
The following is an example.

Switch (ws.readystate) {
Case websocket.connecting:
Do something
Break
Case Websocket.open:
Do something
Break
Case websocket.closing:
Do something
Break
Case websocket.closed:
Do something
Break
Default
This never happens
Break
}
3. Callback function
The OnOpen property of the instance object that specifies the callback function after the connection succeeds.

Ws.onopen = function () {
Ws.send (' Hello server! ');
}
If you want to specify more than one callback function, you can use the AddEventListener method.

Ws.addeventlistener (' Open ', function (event) {
Ws.send (' Hello server! ');
});
4. Close the callback function
The OnClose property of the instance object that specifies the callback function after the connection is closed.

Ws.onclose = function (event) {
var code = Event.code;
var reason = Event.reason;
var wasclean = Event.wasclean;
Handle Close Event
};

Ws.addeventlistener ("Close", function (event) {
var code = Event.code;
var reason = Event.reason;
var wasclean = Event.wasclean;
Handle Close Event
});
5. callback function after specifying server data
The OnMessage property of the instance object that specifies the callback function after the server data is received.

Ws.onmessage = function (event) {
var data = Event.data;
Working with Data
};

Ws.addeventlistener ("Message", function (event) {
var data = Event.data;
Working with Data
});
Note that the server data may be text or binary data (BLOB objects or Arraybuffer objects).

Ws.onmessage = function (event) {
if (typeof event.data = = = String) {
Console.log ("Received data string");
}

if (event.data instanceof ArrayBuffer) {
var buffer = Event.data;
Console.log ("Received arraybuffer");
}
}
In addition to dynamically judging the type of data you receive, you can also use the Binarytype property to explicitly specify the binary data type you receive.

The BLOB data is received
Ws.binarytype = "blob";
Ws.onmessage = function (e) {
Console.log (e.data.size);
};

I got ArrayBuffer data.
Ws.binarytype = "Arraybuffer";
Ws.onmessage = function (e) {
Console.log (e.data.bytelength);
};
6. Sending data to the server
The Send () method of the instance object is used to send data to the server.
Example of sending text.

Ws.send (' your message ');
Example of sending a Blob object.

var file = document
. Queryselector (' input[type= "file"] ")
. Files[0];
Ws.send (file);
Example of sending a ArrayBuffer object.

Sending Canvas ImageData as ArrayBuffer
var img = canvas_context.getimagedata (0, 0, 400, 320);
var binary = new Uint8array (img.data.length);
for (var i = 0; i < img.data.length; i++) {
Binary[i] = Img.data[i];
}
Ws.send (Binary.buffer);
7. Error handling methods
The OnError property of the instance object that specifies the callback function when an error occurs.

Socket.onerror = function (event) {
Handle Error Event
};

Socket.addeventlistener ("Error", function (event) {
Handle Error Event
});
8. Data Length Determination
The Bufferedamount property of the instance object that indicates how many bytes of binary data are not sent out. It can be used to determine whether the send is over.

var data = new ArrayBuffer (10000000);
Socket.send (data);

if (socket.bufferedamount = = = 0) {
Send complete
} else {
Delivery's not over yet.
}

Iv. Server aspects
There are a lot of common node
Now, just a special wobsocketd.
Its biggest feature is that the background script is not limited to language, standard input (stdin) is the input of WebSocket, standard output (stdout) is WebSocket output.

For example, here is a Bash script counter.sh.

#!/bin/bash

Echo 1
Sleep 1

Echo 2
Sleep 1

Echo 3
Running this script at the command line will output 1, 2, 3, and each value is 1 seconds apart.

$ bash./counter.sh
1
2
3
Now, start websocketd and specify the script as the service.

$ websocketd--port=8080 bash./counter.sh
The above command launches a WebSocket server with a port of 8080. Whenever the client connects to the server, it executes the counter.sh script and pushes its output to the client.

var ws = new WebSocket (' ws://localhost:8080/');

Ws.onmessage = function (event) {
Console.log (Event.data);
};
This is the client's JavaScript code, which in turn outputs 1, 2, and 3 in the console.
With it, it is convenient to send the output of the command line to the browser.

$ websocketd--port=8080 ls
The command above executes the LS command, which sends the contents of the current directory to the browser. It's easy to monitor the server in real time in this way (code).

For more usage, refer to the official example.
Example of a Bash script reading client input
Five lines of code to implement one of the simplest chat server

The essence of websocketd is the WebSocket agent of the command line. As long as the command line can execute the program, it can communicate with the browser WebSocket. The following is a Node-implemented Echo service greeter.js.

Process.stdin.setEncoding (' UTF8 ');

Process.stdin.on (' readable ', function () {
var chunk = Process.stdin.read ();
if (chunk!== null) {
Process.stdout.write (' data: ' + chunk);
}
});
The command to start the script is as follows.

$ websocketd--port=8080 node./greeter.js
Official warehouses also have examples of various other languages.

Summarize:

The role of WebSocket in instant communication is still relatively large, after all, to solve the Ajax if repeated requests when the large access pressure, so if you have the opportunity to further study it.

WebSocket Simple Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.