1.WebSocket Introduction
1.1 Concepts
WebSocket is a series of new APIs in HTML5, or new specifications, new technologies. The support page uses the Web socket protocol for full-duplex communication with the remote host. It introduces the WebSocket interface and defines a full-duplex communication channel that operates on the web through a single socket.
1.2 WebSocket vs HTTP
First, the development of web technology has undergone the following stages.
static pages (HTML)
Dynamic page (cgi,j2ee,php ...)
Ajax Technology
Comet Technology (polling)
1.2.1 Implementation Scenario Comparison
For a simple example, take the 51cto message push as an example.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/87/E0/wKioL1fj2ZegVnmrAAAbVI4ZPto807.png "title=" Message.png "alt=" Wkiol1fj2zegvnmraaabvi4zpto807.png "/>
Below, we use the technology mentioned to achieve this small function, analysis of the pros and cons.
Static page does not say, it is generally applied at the page cache level, but the message entry obviously has a certain aging, not applicable to the scene.
Dynamic page, in order to update the number of messages, refresh the entire page, all the following pages are re-rendered, efficiency is not added.
Ajax technology, you can implement a partial page refresh, through HTTP polling, get message entries. Even if there is no new message, the request must be sent, resulting in a meaningless request. The request interval is too long, there is a problem with real-time, and the interval is too late, wasting server resources and consuming bandwidth.
Comet technology, based on HTTP long connections, is an implementation of reverse Ajax (Reverse Ajax) that can send data from the server side to the client, enabling the reuse of the connection. There are pros and cons to both ways of implementation. (1) Ajax-based long polling (long-polling) mode, and (2) stream based on Iframe and Htmlfile (HTTP streaming) mode.
WebSocket Implementation Scenarios
Unlike the HTTP protocol's different request/response modes, the HTML5 Web sockets efficiently provides Web connectivity with minimal overhead, greatly reducing unnecessary network traffic and latency. A Web client connects to a remote endpoint via WebSocket for full-duplex communication, improves real-time, and does not have a waste of service resources.
1.2.2 WebSocket and HTTP relationships
Both are the application Layer development specifications, WebSocket is based on HTTP, WebSocket is actually a new protocol, and the HTTP protocol is basically not related, just to be compatible with the existing browser handshake specification.
HTTP supports long connections, but WebSocket is a persistent connection.
1.3 WebSocket Scene
1. Social subscription
2. Multi-player game
3. Collaborative editing/programming
4. Tap Stream data
5. Stock Fund Quotes
6. Live Sports Update
7. Multimedia Chat
8. Location-based applications
9. Online Education
2. My WebSocket Project
The project is still being perfected. It contains several examples of websocket. Examples include game class, Chat class, artboard class ....
I, I prefer to learn a technical principle of "run anyway first", collect these examples, spent nearly 3 days of personal time.
Hope to be useful to everyone.
Project Address: Https://github.com/janecms/websocket_example
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/87/E4/wKiom1fj45qhDh3sAAB9sxuFA_I364.png "title=" Git.png "alt=" Wkiom1fj45qhdh3saab9sxufa_i364.png "/>
3. Two ways to declare a server-side WebSocket service (Endpoint)
The main content is the declaration of endpoint.
Create a service-side step
Create an endpoint class.
Implement the lifecycle methods of the endpoint.
ADD your business logic to the endpoint.
Deploy the endpoint inside a Web application.
3.1 Programming Type
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/87/E4/wKiom1fj6lexCyNMAAASjmxStS8245.png "title=" Endpoint.png "alt=" Wkiom1fj6lexcynmaaasjmxsts8245.png "/>
The Onopen,onclose,onerror in endpoint corresponds to the life cycle of the websocket.
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/87/E1/wKioL1fj6sGTA5iQAABKQnIo85Y518.png "title=" Lifecycle.png "alt=" Wkiol1fj6sgta5iqaabkqnio85y518.png "/>
1. Create Endpoint
public class Echoendpoint extends Endpoint {@Override public void OnOpen (final session session, Endpointconfig Config {Session.addmessagehandler (new messagehandler.whole<string> () {@Override public void onmess Age (String msg) {try {session.getbasicremote (). SendText (msg); } catch (IOException e) {...} } }); }}
2. Deploying Endpoint
ServerEndpointConfig.Builder.create (Echoendpoint.class, "/echo"). Build ();
For details, see:
Https://github.com/janecms/websocket_example in the <websocket.echo.echoendpoint>.
3.2 Annotation Declaration Style
More simple.
@ServerEndpoint ("/echo") public class Echoendpoint {@OnMessage public void OnMessage (Session session, String msg) { try {session.getbasicremote (). SendText (msg); } catch (IOException e) {...} }}
See details
Https://github.com/janecms/websocket_example in the <websocket.echo.echoannotation>.
Related annotation Instructions
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/87/E1/wKioL1fj64uCtxLcAAB4ES7wn0A654.png "title=" Annotation.png "alt=" Wkiol1fj64uctxlcaab4es7wn0a654.png "/>
Each websocket endpoint may only has one message handling method for each of the native WebSocket
Message formats:text, binary and Pong
A endpoint can only have a method that is modified by @onmessage to manipulate the text, binary, pone information. This restriction, the different environment, will differ.
4.HTML5 WebSocket implements the client
The client, which also corresponds to the life cycle. Onopen,onclose,onmessage,onerror.
var wsocket;function connect () {wsocket = new WebSocket ("WS://LOCALHOST:8080/DUKEETF2/DUKEETF"); Wsocket.onmessage = onmessage;//defines the callback websocket.onerror = function (evt) {onerror (evt)}; }function OnMessage (evt) {var ARRAYPV = Evt.data.split ("/"); document.getElementById ("Price"). InnerHTML = Arraypv[0]; document.getElementById ("Volume"). InnerHTML = arraypv[1];} ... window.addeventlistener ("Load", connect, false);
5. WebSocket protocol Interaction Data
and standard HTTP, there is a big difference.
5.1 Request data
Get/path/to/websocket/endpoint Http/1.1host:localhostupgrade:websocketconnection:upgradesec-websocket-key: Xqbt3imnzjbyqrinxeflkg==origin:http://localhostsec-websocket-version:13
5.2 Response Data
http/1.1 101 Switching protocolsupgrade:websocketconnection:upgradesec-websocket-accept:k7djldlooiwig/ mopvwfb3y3fe8=
5.3 WebSocket's request URL, nor is it a standard HTTP schema.
Normal: Ws://host:port/path?query encryption: Wss://host:port/path?query
Reference Resources
Https://www.oschina.net/translate/9-killer-uses-for-websockets
Http://www.tuicool.com/articles/FBbaai
Https://docs.oracle.com/javaee/7/tutorial/websocket.htm
Https://github.com/janecms/websocket_example
Conclusion
This paper mainly describes the similarities and differences between WebSocket and HTTP, as well as the advantages and usage scenarios of websoket. A brief discussion of the declaration of WebSocket in 2. Finally shared their own display projects. Next, through the case of actual combat, walkthrough code decoding, error handling in the use of websocket.
This article is from a "simple" blog, so be sure to keep this source http://dba10g.blog.51cto.com/764602/1855634
WebSocket Combat (1) Getting Started