Reverse Ajax:websocket

Source: Internet
Author: User

Guo Chen Software 151 1531610114

WebSocket

The websocket that appears in HTML5 is a new inverse Ajax technology that is newer than comet, WebSocket enables bidirectional full-duplex communication channels, which are supported by many browsers (Firefox, Google Chrome, and Safari). The connection is opened by an HTTP request called the WebSocket handshake, which uses some special headers. The connection remains active, and you can use JavaScript to write and receive data, just as if you were using an original TCP socket interface.

The starting input for the WebSocket URL is ws://or wss://(on SSL).

The timeline in Figure 1 illustrates the communication using WebSocket. An HTTP handshake with a specific header is sent to the server side, and then the server or client can use JavaScript to access a socket (socket), which can be used to asynchronously receive data through the event handle.

Figure 1. Using WebSocket's Reverse Ajax

There is a websocket example in the source code that can be downloaded in this article, and you should see the output similar to listing 1 when you run the example. It explains how the client's events occur and how they are immediately displayed on the client. When the client sends some data, the server responds to the client's sending behavior.

Listing 1. Examples of websocket in JavaScript

[Client]WebSocket Connection opened
[Server]1Events
[Event]ClientID=0
[Server]1Events
[Event]At Fri June1721st:12:01EDT2011
[Server]1Events
[Event]From0: QQQ
[Server]1Events
[Event] at Fri June 1721: 12:05 2011
[server] 1 events
event] From 0: VV

Typically, in JavaScript you will use WebSocket as described in Listing 2, if your browser supports it.

Listing 2. JavaScript Client Example

VarWs=NewWebSocket (‘Ws://127.0.0.1:8080/async‘);
Ws.onopen=function() {
//Called when the connection is opened
};
Ws.onerror=function(e) {
//Called when an error occurs, such as when the connection is broken
};
Ws.onclose=function() {
//Called when the connection is closed
};
ws.onmessage = function (msg) {
   //    // Msg.data contains the message
};
// here is how to send some data to the server side
Span style= "COLOR: #000000" >ws.send ( "some Data ");
// close socket interface
ws.close ();

The data sent and received can be of any type, and websocket can be seen as a TCP socket, so it depends on what type of data the client and server side know to send back and forth. The example here is to send a JSON string.

After the JavaScript WebSocket object is created, if you look at the HTTP request in the browser's console (or Firebug), you should see the WebSocket-specific header. Listing 3 shows an example.

Listing 3. HTTP request and corresponding header example

Request url:ws://127.0.0.1:8080/async
Request Method:get
Status Code:101WebSocket Protocol Handshake

Request Headers
Connection:upgrade
Host:127.0.0.1:8080
Origin:http://localhost:8080
Sec-websocket-key1:1&1~ 33188YD]R8DP w75q
Sec-websocket-key2:17;229 *043m 8
upgrade:websocket
(Key3): B4:bb:20:37:< Span style= "COLOR: #000000" >45:3f:bc:c7

Response Headers
Connection: Upgrade
Sec-websocket-location:ws://127.0.0.1:< Span style= "COLOR: #000000" >8080/async
sec-websocket-origin:http://localhost:< Span style= "COLOR: #000000" >8080
Upgrade:websocket
(Challenge Response): ac:< Span style= "COLOR: #000000" >23:a5:7e:5d:e5:04:6a:b5:f8:cc:e7:ab:6d:1a:39

The WebSocket handshake uses all of these headers to validate and set a long-lived connection, and the WebSocket JavaScript object also contains two useful properties:

Ws.url: Returns the URL of the WebSocket server
Ws.readystate: Returns the value of the current connection state
1. Connecting = 0
2. OPEN = 1
3. CLOSED = 2

Server-side processing of websocket is slightly more complicated, and there is no Java specification that supports websocket in a standard way. To use the WebSocket functionality of a Web container (such as Tomcat or jetty), you need to tightly couple application code and container-specific libraries to access websocket functionality.

The example code in the WebSocket folder uses the jetty WebSocket API, because we are using the jetty container. Listing 4 shows the handler for the WebSocket. (the 3rd chapter of this series uses different backend WebSocket APIs.) )

Listing 4. WebSocket Handlers for jetty containers

Public Final class Reverseajaxservlet extends Websocketservlet {
@Override
Protected WebSocket Dowebsocketconnect (httpservletrequest request,string protocol) {
Return [...]
}
}

As far as jetty is concerned, there are several ways to deal with websocket handshake, the easier one is to subclass Jetty Websocketservlet and implement Dowebsocketconnect method. This method requires you to return an instance of the jetty WebSocket interface, and you must implement the interface and return some endpoint (endpoint) that represents the WebSocket connection. Listing 5 provides an example.

Listing 5. WebSocket implementation Examples

ClassEndpoint implements WebSocket {
Outbound Outbound;
@Override
PublicvoidOnConnect (Outbound Outbound) {
This. Outbound=Outbound
}
@Override
PublicvoidOnMessage (Byteopcode, String data) {
//Called when a message is received
//That's the way you usually use it.
}
@Override
PublicvoidOnfragment (Boolean more,ByteOpCodeByte[] Data,IntOffsetIntLength) {
//OnMessage is called when a piece of content is completed
//It's not usually written in this way.
}
@Override
Publicvoid OnMessage ( Byte opcode, byte[] data,< Span style= "COLOR: #0000ff" >int offset, int length) {
onMessage (opcode, new String (data, offset, length));
}
@Override
publicvoid OnDisconnect () {
Outbound = null}
} /span>

To send a message to the client, you write a message to outbound, as shown in Listing 6:

Listing 6. Send a message to the client

if (outbound! = null && outbound.isopen ()) {
Outbound.sendmessage ('Hello world!') );
}

To disconnect and close the WebSocket connection to the client, use Outbound.disconnect ().

WebSocket is a powerful way to implement no-delay bidirectional communication, and Firefox, Google Chrome, opera, and other modern browsers support this approach. According to the Jwebsocket website:

1. Chrome starts with a localized websocket from version 4.0.249.
2. Safari 5.x contains localized websocket.
3. Firefox 3.7a6 and 4.0b1+ contain localized websocket.
4. Opera starts with the 10.7.9.67, which includes localized websocket.

For more information on Jwebsocket, please refer to the Resources section.

  Advantages

The WebSocket is powerful, bidirectional, low latency, and easy to handle errors, and does not have many connections like Comet long polling or some of the drawbacks of comet streaming. Its API is also easy to use, without the need for additional layers to be used directly, while comet requires a good library to handle reconnection, timeouts, Ajax requests, confirmations, and the choice of different transports (Ajax long polling and Jsonp polling).

  Disadvantages

The disadvantages of WebSocket have these:

1. is a new specification from HTML5, which has not been supported by all browsers.

2. There is no requesting scope (request scope) because WebSocket is a TCP socket interface instead of an HTTP request, and the scoped request service, such as Hibernate sessioninviewfilter, is not easy to use. Hibernate is a persistence framework that provides a filter on the perimeter of the HTTP request. At the start of the request, it sets a context (including transaction and JDBC Connection) boundaries in the request thread, and at the end of the request, the filter destroys the context.

  Flashsocket

For browsers that do not support websocket, some libraries can be rolled back to Flashsocket (via the Flash's socket interface). These libraries usually provide the same official WebSocket API, but they are implemented by delegating calls to a hidden flash component that is contained in a Web site.

  Advantages

Flashsocket transparently provides websocket functionality, even on browsers that do not support HTML5 WebSocket.

  Disadvantages

Flashsocket has the following drawbacks:

1. It needs to install the Flash plugin (typically, all browsers will have the plugin).

2. It requires that the 843 port of the firewall is open so that the flash component can issue an HTTP request to retrieve the policy file that contains the domain authorization. If the 843 port is unreachable, the library should have a fallback action or give an error, all of which will take some time (up to 3 seconds, depending on the library), which slows down the site.

3. If the client is behind a proxy server, the connection to port 843 may be denied.

The WEBSOCKETJS project provides a bridging approach that requires a minimum of 10 versions of Flash to provide websocket support for Firefox 3, inernet Explorer 8, and Internet Explorer 9.

Reverse Ajax:websocket

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.