WebSocket Introduction (ii)-websocket API

Source: Internet
Author: User
Tags stomp

This chapter describes how to use the WebSocket API to control protocols and create applications, and using the existing WebSocket servers provided by http://websocket.org, we can send and receive messages, and create some simple websocket applications. Step-by-step learning to use the WebSocket API, and finally we'll talk about browser support and connectivity. This chapter focuses on the application of the WebSocket protocol to the Web client, and in a later chapter describes the WebSocket protocol and its usage environment.

Review:

As mentioned in the first chapter, WebSocket contains network protocols and APIs that allow you to create websocket connections on both the client and server side, and the third chapter discusses the details of the protocol in detail, so let's look at the API first. WebSocket API is actually a interface using the WebSocket protocol, through which to establish a full-duplex channel to send and receive messages, easy to learn, to connect to a remote server, only need to create a WebSocket object entity, and pass in a server-side URL. During the start of the handshake between the client and the service side, the HTTP protocol is upgraded to the WebSocket protocol to establish a connection, with the underlying TCP protocol. Once the connection is established, the message can be sent repeatedly through the WebSocket interface. Inside your code, you can use asynchronous events to listen to each phase of the connection lifecycle. The WebSocket API is purely event driven, and once a full-duplex connection is established, when the server sends data or resources to the client, it can automatically send state-changed data and notifications. So you don't need to go to rotation server for status updates and listen to the client. In subsequent chapters we will introduce more advanced protocols, such as Stomp and XMPP, which will learn different examples of WebSocket API usage, but now look at the API carefully.

Entry:

First, we need to create a websocket connection by calling the WebSocket constructor, which returns a WebSocket instance that can be used to listen for events. These events will tell you when the connection is established, when the message arrives, when the connection is closed, and when the error occurred. The WebSocket protocol defines two URL schemes, where WS and WSS represent unencrypted and encrypted communication between the client and the server. WS (WebSocket) is similar to HTTP URLs, while the WSS (WebSocket security) URL indicates that connections are based on the Secure Transport Layer (TLS/SSL) and HTTPS connections are the same security mechanism. The WebSocket constructor requires a URL parameter and an optional protocol parameter (the name of one or more protocols), the parameters of the protocol such as XMPP (extensible Messaging and Presence Protocol), SOAP (simple Object Access Protocol) or a custom protocol. The URL parameter needs to start with ws://or wss://, for example: ws://www.websocket.org, if the URL has a syntax error, the constructor throws an exception.
// Create New WebSocket connection var New WebSocket ("ws://www.websocket.org"); // test the next link is not on. 

The second parameter is the protocol name, is optional, the server and the customer service side to use the protocol must be consistent, so that send and receive messages to understand each other, you can define one or more clients to use the protocol, the server will choose one to use, a customer service side and a server can only have one protocol.    Of course, one of the major benefits of Websocket,websocket is that, based on the extensive use of the WebSocket protocol, your web can have the same capabilities as traditional desktop programs, which we'll learn in section sixth of the third chapter. In return, we go back to the constructor, after the first handshake, and the name of the protocol, the client sends a SEC-WEBSOCKET-PROTOCOL header, and the server chooses 0 or one protocol, and the response takes the same Sec-websocket-protocol header. Otherwise, the connection is closed. With protocol negotiation (Protocol negotiation), we can know the protocols and versions supported by a given WebSocket server, and then apply the selection protocol to use.
// Connecting to the server with one protocol called MyProtocol var New WebSocket ("ws://echo.websocket.org", "MyProtocol"); // MyProtocol is a well-defined and standard-compliant protocol that is assumed. 

You can pass an array of protocols.

var New WebSocket ("ws://echo.websocket.org", ["Com.kaazing.echo", "Example.imaginary.protocol"])//  The server will select one of the use function(e) {///  Check The protocol chosen by the Console.log (Echosocket.protocol);}

Output: Com.kaazing.echo

The protocol has three parameters. 1. Registration Agreement: The standard agreement that is officially registered under RFC6455 (WebSocket Agreement) and IANA. For example, Microsoft Soap. For more information: Http://www.iana.org/assignments/websocket/websocket.xml See two Huawei 2. Open protocols: Widely used labeling protocols, such as XMPP and stomp. But not officially registered. 3. Custom protocol: The WebSocket protocol that you write and use. The agreement will be detailed in the following chapters, which look at events, objects and methods, and examples. WebSocket event: The WebSocket API is purely event-driven and can handle incoming data and changed link state by listening for events. The client does not need to rotation the server in order to update the data. After the server sends the data, the messages and events arrive asynchronously. WebSocket programming follows an asynchronous programming model that simply adds a callback function to the WebSocket object to listen for events. You can also use the AddEventListener () method to listen. And a WebSocket object is divided into four different kinds of events. Open: The Open event is triggered once the server responds to a WebSocket connection request. The callback function of the response is called OnOpen.
// Event handler for the WebSocket connection opening function (e) {console.log ("Connection open ...") ;

When the Open event is triggered, it means that the protocol handshake is complete and the websocket is ready to send and receive data. If your app receives an open event, you can determine that the server has processed the request to make the connection and agree to communicate with your app.

Message: When a message is accepted, it triggers a messages event, and the response callback function is called OnMessage. As follows:
// event handling instances that accept text messages: function (e) {if(typeof E.data = = = = "string") {Console.log ("string message Received" )  Else  {console.log ("other message Received", E, e.data);}};

In addition to text messages, the WebSocket message mechanism can also handle binary data, with BLOBs and arraybuffer of two types that need to determine the type of data before reading to the data.

 //  set binary data type to BLOB (default type)  Ws.binarytype = "blob"  //  ws.onmessage = function   if  (E.data instanceof   blob) {Console.log ( "blob message received" , e.data);  var  blob = new   Blob (e.data);}};  
// ArrayBufferws.binarytype = "ArrayBuffer"function(e) {if  instanceof  ArrayBuffer) {console.log ("ArrayBuffer Message Received", + e.data); // E.data is the Arraybuffer type var New Uint8array (E.data);}};
ErrorIf an unexpected failure triggers an error event, the corresponding function is called onerror, and the error causes the connection to close. If you receive an error event, you will soon receive a shutdown event that may tell you the cause of the error in the Shutdown event. The handling of error events is more appropriate for the re-connected logic.
// Exception Handling function (e) {console.log ("WebSocket Error:" , e); // Custom function for handling errors handleerrors (e);};
Close goes without saying that when the connection is closed, the event is triggered, corresponding to the OnClose method, and after the connection is closed, the server and the client can no longer send and receive messages. The WebSocket specification also defines the ping and Pong architecture (frames), which can be used to do keep-alive, heartbeat, network status queries, latency instrumentation (delayed instrumentation?). ), but the WebSocket API has not yet published these features, although the browser supports ping but does not trigger a ping event, instead the browser automatically responds to Pong, and the eighth chapter will have more details about pings and pong.

Of course you can call the Close method to break the link to the server to trigger the OnClose event,

function (e) {console.log ("Connection closed", e);};

Both the connection failure and the successful close handshake trigger the Shutdown event, and the ReadyState property of the WebSocket object represents the state of the connection (2 is closing and 3 is closed). The Shutdown event has three properties that can be used to do exception handling and regain: wasclean,code and reason.   Wasclean is a bool value that represents whether the connection is cleanly closed. If it is a response to the close event on the service side, this value is true if it is a different reason, for example, because the underlying TCP connection is down, Wasclean is false. Code and reason represent the state of the server sent when the connection is closed, and the two properties correspond to the code and reason parameters given to the Close method, and the details are described later.

WebSocket Method:

WebSocket objects have two methods: Send () and close ()

Send ():

Once a full duplex bidirectional connection is established on the server and the client, you can use the Send method to send the message.

// send a text message ws.send ("Hello websocket!");

The Send () method transmits data when the connection is open, and throws an exception when the connection is closed or not obtained. A common mistake is that people like to send messages before they connect to open. As shown below:

// This will not work var New WebSocket ("ws://echo.websocket.org") ws.send ("Initial data");

The correct posture is as follows, and you should wait for the open event to fire before sending a message.

var New WebSocket ("ws://echo.websocket.org"function(e) {ws.send ("Initial data");}

If you want to send a message by responding to another event, you can check that the value of the ReadyState property is open.

function MyEventHandler (data) {if (ws.readystate = = = Websocket.open) {//OPEN can be sent       else {//do something else  // possibly ignore the data or enqueue it. }}

Send binary data:

// Send a Blob var New Blob ("Blob contents"); Ws.send (BLOB); // Send an ArrayBuffer var New Uint8array ([8,6,7,5,3,0,9]); Ws.send (a.buffer);

The Blob object and the JavaScript file API are useful when used together and can send or receive files, most of the multimedia files, images, video and audio files. At the end of this chapter, the file API is combined to provide an instance code that reads the contents of a websocket message.

Close ()

Use the Close method to close the connection, and if it is connected and closed, this method will do nothing. After you call the Close method only, you will not be able to send data.

Ws.close ();

The Close method can pass in two optional arguments, code (numerical) and Reason (string), to tell the server why the connection was terminated. The third chapter discusses these two parameters in detail when we close the handshake.

// successful end of Session Ws.close ("Closing normally"); // 1000 is the status code, which represents the normal end. 
WebSocket Property

The WebSocket object has three properties, Readystate,bufferedamount and protocol.

ReadyState:

The WebSocket object communicates the connection state through the read-only attribute readystate, which automatically changes the connection state. The following table shows the four different values for the ReadyState property.

Property Value State
Websocket.connecting 0 Connection is in progress, but not yet established
Websocket.open 1 The connection is already established and can send messages.
Websocket.closing 2 The connection is closing the handshake
Websocket.closed 3 The connection is closed or cannot be opened

Understanding the status of the current connection helps us debug.

Bufferedamount: Sometimes it is necessary to check the size of the transmitted data, especially when the client transmits a large amount of data. Although the Send () method executes immediately, the data is not transmitted immediately. The browser caches the data out of the app, and you can use the Bufferedamount property to check the size of the data that has been queued but not yet transferred. This value does not include the protocol framework, operating system cache, and network software overhead. The following example shows how to use the Bufferedamount property to update the send every second. If the network cannot handle this frequency, it will be adaptive.
//10kvarTHRESHOLD = 10240;//Establish a connectionvarWS =NewWebSocket ("ws://echo.websocket.org");//Listen for the opening eventWs.onopen =function() {setinterval (function() {//send when the cache is not fullif(Ws.bufferedamount <THRESHOLD) {Ws.send (Getapplicationstate ());}},1000);};//using the Bufferedamount property to send data avoids network saturation. 
Protocol

In the constructor, the protocol parameter lets the server know the WebSocket protocol used by the client. This property of the WebSocket object refers to the protocol name identified by the end server, which is empty when the server does not select the protocol provided by the client or before the connection handshake ends.

Full instance

Now that we've passed the WebSocket constructors, events, properties, and methods, the next step is to learn the WebSocket API through a complete example. The instance uses the "Echo" server: ws://echo.websocket.org, which is able to accept and return data that was sent past. This helps to understand how the WebSocket API interacts with the server. First, we establish the connection, let the page show the client connection service side of the information, and then send, accept the message, and finally close the connection.
  < H2 > Websocket Echo Client</h2>    <id= "Output "></div>
     //initializing connections and events        functionSetup () {Output= document.getElementById ("Output"); WS=NewWebSocket ("Ws://echo.websocket.org/echo"); //Monitor OpenWs.onopen =function(e) {log ("Connected"); SendMessage ("Hello websocket!"); }            //Monitoring CloseWs.onclose =function(e) {log ("Disconnected:" +E.reason); }            //Monitor ErrorsWs.onerror =function(e) {log ("Error"); }            //Monitor MessagesWs.onmessage =function(e) {log ("Message Received:" +e.data); //Close when message is receivedWs.close (); }        }        //Send Message        functionsendMessage (msg) {ws.send (msg); Log ("Message Sent"); }        //Logging        functionlog (s) {varp = document.createelement ("P"); P.style.wordwrap= "Break-word"; P.textcontent=s;            Output.appendchild (P); //Also Log information on the JavaScript consoleConsole.log (s); }        //StartSetup ();

WebSocket Introduction (ii)-websocket API

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.