Web Message Push-comet4j

Source: Internet
Author: User
Tags java web

First, Comet Introduction:

Comet: "Server Push" technology based on HTTP long Connections is a new WEB application architecture. In an application based on this architecture, the server side proactively pushes the data to the client program asynchronously, without requiring the client to make explicit requests. The Comet architecture is ideal for event-driven WEB applications, as well as for applications where interactivity and real-time requirements are strong, such as stock market analysis, chat rooms, and Web version online games.

Second, comet4j functional characteristics
    • Push message broadcast.
    • Pushes a directed message.
    • Provide a variety of processing events, such as pre-launch, on-line, pre-line, offline, send message, etc.
    • The message caching mechanism ensures that the message is not lost in long polling operation mode.
    • The client is offline and the server is immediately aware.
    • The client stops working abnormally and the server can check and sense it regularly.
    • In the way of registering channel application, let the developer extend the framework function to realize their own application.
Three, comet4j frame characteristics
    • Independent and compact, not dependent on third-party packages.
    • Tightly integrated with applications without the need for standalone applications or servers.
    • A connection mechanism that is unrelated to the session, providing the developer with the maximum level of functional controllability.
    • Event-oriented programming, both client and server are event-driven development models, providing good extensibility mechanisms.
    • Each performance parameter can be configured.
    • Supports a variety of mainstream browsers and supports the air application environment.
Iv. Practical Application of comet4j

(1) Download the jar package and JS file required by comet4j. Specific: http://code.google.com/p/comet4j/

(2) New Web project: Project Demo:http://pan.baidu.com/s/1hqsupzi

    

(3) In the demo, it can be found that the channel used in the index.jsp must be consistent with the channel set in the Comet4j.java, in the whole push,

The singleton pattern is used, so developers don't have to worry that it consumes a lot of memory.

(4) COMET4J development is simple, just refer to its client and Server API documentation, make the push function you want should be no problem.

The second kind: we are more familiar with

I. WebSocket Brief INTRODUCTION

I. WebSocket Brief Introduction
With the development of the Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex needs of web applications. In recent years, with the birth of HTML5, the WebSocket protocol has been proposed, it realizes full duplex communication between browser and server, expands the communication function between browser and service, and enables the server to send data to the client actively.$ j6 S6 p/d (k-g ' m
We know that the traditional HTTP protocol is stateless, each request must be initiated by the client (such as a browser), the server to return response results after processing, and the service side is very difficult to actively send data to the client, the client is the active side, The traditional Web mode with the passive side of the server is less troublesome for Web applications where information is not changing frequently, but it is inconvenient for Web applications involving real-time information, such as applications with instant messaging, real-time data, and subscription push. Before the WebSocket specification was introduced, developers would often use a compromise solution: polling (polling) and comet technology to achieve these real-time features. In fact, the latter is also a kind of polling, but some improvement.
Polling is the most primitive solution for implementing real-time Web applications. Polling technology requires clients to periodically send requests to the server at set intervals, frequently querying for new data changes. Obviously, this approach leads to excessive unnecessary requests, wasteful traffic, and server resources.
Comet technology can also be divided into long polling and streaming technology. Long polling improves the polling technology mentioned above, reducing useless requests. It sets the expiration time for some data and sends the request to the server when the data expires, a mechanism suitable for data changes that are not particularly frequent. Streaming technology usually refers to the client using a hidden window and the server to establish an HTTP long connection, the server will constantly update the connection state to keep the HTTP long connection to survive, so that the server can use this long connection to actively send data to the client; streaming technology in a large concurrency environment, May test performance on the server side.
Both of these technologies are based on the request-response model, which is not really real-time technology; Each request and response wastes a certain amount of traffic on the same header information, and the complexity of the development is greater.. C W (i) E4 K. P, M; G
With the launch of the HTML5 WebSocket, the real real-time communication of the web, so that b/s model with the C/s mode of real-time communication capabilities. WebSocket Workflow is this: the browser through JavaScript to the server to establish a WebSocket connection request, after the WebSocket connection is established successfully, the client and the server can transfer data over a TCP connection. Because the WebSocket connection is essentially a TCP connection and does not require duplicate header data per transmission, it has a much smaller data transfer than polling and comet technology. This article does not introduce the WebSocket specification in detail, mainly introduces the implementation of the next websocket in the Java Web.# k-l0 {# I. k
Java EE 7 shows the Jsr-356:java API for WebSocket specification. Many web containers, such as Tomcat,nginx,jetty, support WebSocket. Tomcat starts with support for WebSocket from 7.0.27, supports JSR-356 from 7.0.47, and the following demo code needs to be deployed in versions above Tomcat7.0.47 to run.# W "f) D, @: u) Y0 L ' ~

Ii. Introduction of WebSocket Agreement
The WebSocket protocol is a two-way communication protocol that is based on TCP and transmits data over TCP as HTTP, but it differs from HTTP by a maximum of two points: 1. WebSocket is a two-way communication protocol, after establishing a connection, the WebSocket server and Browser/ua can actively send or receive data to each other, just like a socket, The difference is that WebSocket is a simple analog socket protocol based on Web, 2. WebSocket need to be connected via a handshake, similar to TCP It also requires a handshake connection between the client and server to communicate with each other after the connection is successful. The simple timing diagram for building a handshake is as follows:+ H; ~; Q4 '/{
<ignore_js_op>
Handshake process:
The browser and the WebSocket server establish a connection through a TCP three handshake, and if this connection fails, the subsequent procedure will not be executed and the Web application will receive an error message notification.
After TCP establishes the connection successfully, BROWSER/UA transmits the WebSocket supported version number through the HTTP protocol, the Word version number of the Protocol, the original address, the host address and so on some column fields to the server side.
After the WebSocket server receives the handshake request sent by Browser/ua, if the packet data and format are correct, the client and server side protocol version number matches, and so on, accepts this handshake connection, and gives the corresponding data reply, the same reply packet is also transmitted by HTTP protocol.-S "J: [-C" O-k
Browser received the server reply to the packet, if the contents of the packet, the format is not a problem, it means that the connection is successful, triggering the OnOpen message, the web developer can at this time through the send interface to the server to send data. Otherwise, the handshake connection fails, and the Web application receives the ONERROR message and knows why the connection failed.5 V, K5? 2 L7 M (\2 b H
' Z7 G9 W, d$ o% k) U
iii. websocket Architecture in Tomcat 73 E7 S, g+ f% r% U4 Y% '
) F ' S5 |4 q-w
, because the websocket communication is divided into handshake and data transmission two processes, two processes need to use the processing method is not the same, the handshake process is based on HTTP 1.1, and the data transmission is directly based on TCP stream transmission.']4 r-c L! S5 x; y* J
In the handshake process, on the basis of HttpServletRequest, the Wshttpservletrequest class is encapsulated, and the invalidation operation function invalidate () is added to the request. In data communication, the process of receiving and processing The class Streaminbound used to process the data input stream is repackaged based on Org.apache.coyote.http11.upgrade.UpgradeInbound, and the classes generated for message processing are extended on the basis of Streaminbound MESSAGEINB Ound. In both data processing classes, there are ondata,ontextdata/onbinarydata,onopen,onclose and other event manipulation function interfaces that implement the business logic in the loaded code class. In the class Wsoutbound for the data output stream, the Upgradeoutbound object instance is encapsulated, and the processing logic related to WebSocket response is added based on the Upgradeoutbound object. Here the processing function is the function of the synchronous call, which guarantees the timing of the websocket response.
The processing flow of websocket in Tomcat is as follows:<ignore_js_op>
Receive the handshake request from the client, COYOTE.HTTP11 Connector to parse the socket, form httpservletrequest send to container.
The corresponding websocketservlet in container processes the request, if the connection request is not accepted, returns, such as accepting the connection request, responding to the request and establishing a socket connection for the client and the server.
The server can now send data to the client via Wsoutbound, while listening to the socket through Streaminbound./D3 C $ S ' N4 S "M
If you receive data from the client, the socket data is parsed into a frame, the frame type is judged, and the data is distributed through events to different logical processes.
When data is returned, call Wsoutbound to encapsulate the returned data and send it to the client.

Iv. code Implementation and requirements

1, the project needs, the timing to all online users to push an ad or push a notification or the like (such as server upgrade, please save the work at hand and so on).: F |, D6 R _0 ~ D
' P ', F0 y* g4 B. G9]# '
2, related environment, Nginx, TOMCAT7, CentOS 6.5
7} M0 r% \$ F ' U1 A
3, the project framework, SPRINGMVC 4.0.6,Layer
! U-q0 {: B2 u-e. ' 6 G
4, the Code implementation:) W r/n6 u/c& l/t3 R) a& h

Websocketconfig:
  1. Import Websocket.handler.SystemWebSocketHandler; $ ', d+ H. H9 E J7 R
  2. @Configuration
  3. @EnableWebMvc
  4. @EnableWebSocket9 Z9 L6 i "h) G4 g$ S" ^& Q
  5. public class Websocketconfig extends Webmvcconfigureradapter implements websocketconfigurer{6 K%]3 U1 o# C {% n
  6. @Override+ j+ '% d% m |3 J6 I7 A + u ' \
  7. public void Registerwebsockethandlers (Websockethandlerregistry registry) {
  8. Registry.addhandler (Systemwebsockethandler (), "/websocketserver"); 4 H0 k% Y9 o8 '/L6 Y7 w/b ' n
  9. Registry.addhandler (Systemwebsockethandler (), "/sockjs/websocketserver");
  10. }
  11. @Bean' \6], M4}% f ' E ' U "\
  12. Public Websockethandler Systemwebsockethandler () {
  13. return new Systemwebsockethandler (); : S-|& u#}/C "g$ v5 a
  14. }
  15. }
Copy Code systemwebsockethandler:
  1. public class Systemwebsockethandler extends Textwebsockethandler {
  2. %}-U "Q6 d# F # p# W; P2 D
  3. Private static final arraylist<websocketsession> users = new arraylist<websocketsession> (); 4? + A. v$ y/}& H
  4. X-y) R8 u/n; m+ y$ L
  5. public void Afterconnectionestablished (Websocketsession session) throws Exception {
  6. System.out.println ("connectionestablished");
  7. Users.add (session); % X7 y-v (\* u! ^
  8. System.out.println ("Current User" +users.size ());
  9. }! K5 d ' v$ [3 B, U5 L, Z
  10. /**(b# S3}0}*?; x* ^
  11. * This method is called when the UI is calling Websocket.send () with JS
  12. * @Author Zhang Zhibong 7 f& a# K4 G8 X. Z |) S3 K
  13. * @param session
  14. * @param message-N) Q; I2? 5 Y, D4 m
  15. * @throws Exception
  16. * @Date March 4, 2016
  17. * Update log & N. c% Q; y#]
  18. * March 4, 2016 Zhang Zhibong first created
  19. *
  20. */
  21. @Override
  22. protected void Handletextmessage (websocketsession session,5 L.}, A5 J4 W8 J, u% x
  23. TextMessage message) throws Exception {(P! W T. h$ g* U8 W
  24. Super.handletextmessage (session, message);
  25. Sendmessagetousers (Session,message);
  26. }
  27. @Override9 m3 D (b# t% r "Z0 e
  28. public void Handletransporterror (websocketsession session, Throwable exception) throws IOException {
  29. if (Session.isopen ()) {% x j0 i! c0 S5 Y
  30. Session.close ();
  31. }
  32. Users.remove (session); 5 @6 y! f$ K, d-s/N9 v5 V
  33. }) M1 |, Z8 R $]0 B
  34. @Override
  35. public void Afterconnectionclosed (websocketsession session, Closestatus Closestatus) throws Exception {& u* X6 C/ n}. ?. E2 W
  36. Users.remove (session); , O,? 0 A. J7 O2 Z6 ' b
  37. }8 p# X, 0 M7 ' + J
  38. % V3 r% E, M; }1]5 D
  39. @Override) A1 [; k/}6 D% [! ^
  40. public Boolean supportspartialmessages () {& Y ' n& u! ~* z (m! h* {. f
  41. return false;
  42. } T9]* K% z7 C (C # E | | f+ i
  43. /**! Z3 l$ S ' Q. \1 g-p: I3 {. D1 E9 W
  44. * Send messages to all online users
  45. * @Author Zhang Zhibong
  46. * @param message void* Y) ' $ f0 T4 m+ b6 q8 X2 P5 F
  47. * @Date March 4, 2016
  48. * Update log 1 q% I4 Y E. @. z# h-e
  49. * March 4, 2016 Zhang Zhibong first created
  50. *5 V5 U3 A + G5 r# p+ F, y/{
  51. */2 H6 z3 a/m4? 0 h (-o% X
  52. public void Sendmessagetousers (websocketsession session,textmessage message) {/L f:d! @ "[% g%]% j!? ]
  53. for (Websocketsession user:users) {
  54. try {; K! [3 K] B! }. V
  55. if (User.isopen ()) {
  56. User.sendmessage (message);  ,? $ R7 A%? N1]. [7 @$ J
  57. }
  58. } catch (IOException e) {
  59. E.printstacktrace (); : C1 t* | j$ i% O4 T8 H
  60. }%]6 X6 _9 e) z, ') j% '! H2 N
  61. }
  62. }2 ^# o (i ' (h ' Z7 L
  63. }
Copy Code Information input index.html:-z& k; W5 d$ U1 ~ (~* T
  1. 7 A8 F3 O5 v; b# G3 B: ^
  2. <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
  3. <title> Please enter any message </title>
  4. <script type= "Text/javascript" src= "Js/jquery-1.10.2.min.js" ></script>7 @ (L1 e# @) X
  5. <script src= "Http://cdn.sockjs.org/sockjs-0.3.min.js" ></script>
  6. <script type= "Text/javascript" >
  7. var ws = NULL;
  8. $ (function () {
  9. if (' WebSocket ' in window) {
  10. WS = New WebSocket (' Ws://127.0.0.1:8080/websocketserver '); 5 s+ J {# E8 F2 O (^2 L8 a:f: F "D
  11. }
  12. else if (' mozwebsocket ' in window) {$ j1}4 r% _-_& Z3 F
  13. WS = New Mozwebsocket ("Ws://127.0.0.1:8080/websocketserver");
  14. }
  15. else {
  16. WS = New Sockjs ("Ws://127.0.0.1:8080/websocketserver"); + p& w:? * O ' _/[6 e ' t, {0 F
  17. }. v-m! b& '; F0 P3 C5 T
  18. Ws.onopen = function () {/b$ e q$ B) D
  19. /k$ L6 b6 S7 m2 J ' A; M/j
  20. };
  21. Ws.onmessage = function (event) {3 o! H. f! h$ M7 q* m:s2 Y
  22. "V1 p. q# '/K
  23. };
  24. Ws.onclose = function (event) {
  25. 6 D7 _ "h$?, Y
  26. }; ! E8}; O, ^! } (o, Q2 R6 \+ Z. O (M
  27. });
  28. function Stop () {+ x8 U6 s7 p. C (U; G0 I
  29. var message = $ ("#message"). Val (); $ w. U:e "P5"! I
  30. Ws.send (message); 6 G U8 P3 A (O |5 W8 G8 [
  31. }
  32. </script>u% \ M8 B7 O0 D5 T5 H "_
  33. 9 U h/y, ^ ' m-f# N
  34. <body class= "Kebody" > X0 d& H9 U5 D (E0 c:f/': R) Q
  35. Please enter a message: <textarea id= "message" ></textarea><br/>
  36. <input type= "button" value= "Start"/>
  37. </body>5% i; H6? 2 b4 M. [/f/b+ J
Copy Code 6 q0 f$ y& l T8 y "A (U (i& n
websocket.js is used to import projects.
  1. document.write ("<script language=javascript src= ' http://127.0.0.1:8080/js/jquery-1.10.2.min.js ' ></ Script> ");
  2. document.write ("<script language=javascript src= ' http://127.0.0.1:8080/layer/layer.js ' ></script>"); ; Z "f* y3 X" ^* A6 {! Q9 @ (M
  3. document.write ("<script language=javascript src= ' http://cdn.sockjs.org/sockjs-0.3.min.js ' ></script>" );
  4. var ws = NULL; 0 K ' _) I, _ (z: | (t$ B. G
  5. var basepath = "ws://127.0.0.1:8080/"; 9 I2 {9 P1 H ' T9 B ' U
  6. if (' WebSocket ' in window) {# W8 n+ P "V, f/v% K
  7. WS = New WebSocket (basepath+ ' websocketserver '); 4 Q. z! u% I (i '}. T) O1 |
  8. }
  9. else if (' mozwebsocket ' in window) {
  10. WS = New Mozwebsocket (basepath+ "Websocketserver"); 0}9 y3 Y9 t% m3?/[; b; Y7 P
  11. }
  12. else {, p. l% Z1 e6 t/d. M8 q
  13. WS = New Sockjs (basepath+ "Sockjs/websocketserver");
  14. }"C8 Y7 f/c.} # [& w# G
  15. Ws.onopen = function () {
  16. + j/t-R4 L "D) [' B9 L2 T
  17. }; 3 R6 @8 v! B1 k# O
  18. Ws.onmessage = function (event) {
  19. Pop (event.data); -C6 d! {5 ^1 q5 a
  20. };
  21. Ws.onclose = function (event) {
  22. Ws.close (); 1 \8 x$ [-O2 \/Z
  23. };
  24. Prompt information
  25. function Pop (message) {.] q%}1 '; B
  26. Layer.alert (message); * d4 H2 B0}) I (J, ~, K
  27. }
Copy Code 9 \; ^. d:m; Y% O5 B2 [
5, in the project head introduction% D0 _; W8 y) {(C:n6 e$ K
<script language=javascript src= ' http://127.0.0.1:8080/webSocket.js ' ></script>


At this point, you will see the following information to illustrate the success. # T; \, y% L c+ d1 ~% U
<ignore_js_op>

then open the page index.html enter the following to click Start. /d% h3 B% D: \9 E
<ignore_js_op>

If there is a hint on the Web site that the configuration is successful, all Web site users can receive this information. , N5 ^, y) H4 C2]3 c*}
<ignore_js_op>

Web Message Push-comet4j

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.