Ajax-based long polling (long-polling) method for simple chat room programs

Source: Internet
Author: User
Tags message queue

Principle:

can see: http://yiminghe.javaeye.com/blog/294781

The advent of AJAX makes it possible for JavaScript to invoke the XMLHttpRequest object to make an HTTP request, and the JavaScript response handler updates the display of the HTML page based on the information returned by the server. Using AJAX to achieve "server push" differs from traditional AJAX applications in that:

    1. Server-Side requests are blocked until a data pass or timeout is returned.
    2. The client-side JavaScript response handler functions to re-establish the connection after processing the information returned by the server, making a request again.
    3. When the client processes the received data, re-establishes the connection, the server side may have new data arrival; The information is saved by the server until the client re-establishes the connection, and the client will retrieve all the information from the current server at once.

The code for the chat page:

Define Mm.js, define the Send message, define the JS function to receive the message

View Plaincopy to Clipboardprint?
  1. Ext.onready (function () {
  2. Getmsg ();
  3. });
  4. function getmsg () {
  5. Ext.Ajax.request ({url: "getmsg", Callback:function (options, success, response) {
  6. if (success) {
  7. Ext.DomHelper.append (Ext.get ("main"), Response.responsetext, true);
  8. }
  9. Getmsg ();
  10. }});
  11. }
  12. function Putmsg () {
  13. Ext.Ajax.request ({url: "putmsg", params:{message:document.getelementbyidx_x_x ("message"). Value}});
  14. }

Here is the servlet that gets the message

View Plaincopy to Clipboardprint?
  1. Package Hyjc.listener;
  2. Import java.io.IOException;
  3. Import Java.io.PrintWriter;
  4. Import javax.servlet.ServletException;
  5. Import Javax.servlet.http.HttpServlet;
  6. Import Javax.servlet.http.HttpServletRequest;
  7. Import Javax.servlet.http.HttpServletResponse;
  8. public class Getmsg extends HttpServlet {
  9. public void doget (HttpServletRequest request, httpservletresponse response)
  10. Throws Servletexception, IOException {
  11. Response.setcontenttype ("text/html");
  12. PrintWriter out = Response.getwriter ();
  13. Messagelist m = messagelist.getinstance ();
  14. Boolean end = false;
  15. while (!end) {
  16. System.out.println ("before get");
  17. String msg = M.get ();
  18. System.out.println ("After get" + msg);
  19. Out.write (msg + "
    ");
  20. if (M.isempty ()) {
  21. end = true;
  22. }
  23. }
  24. Out.close ();
  25. }
  26. public void DoPost (HttpServletRequest request, httpservletresponse response)
  27. Throws Servletexception, IOException {
  28. Doget (request, response);
  29. }
  30. }

Here is the servlet that adds the message

View Plaincopy to Clipboardprint?
  1. Package Hyjc.listener;
  2. Import java.io.IOException;
  3. Import Java.io.PrintWriter;
  4. Import javax.servlet.ServletException;
  5. Import Javax.servlet.http.HttpServlet;
  6. Import Javax.servlet.http.HttpServletRequest;
  7. Import Javax.servlet.http.HttpServletResponse;
  8. public class Putmsg extends HttpServlet {
  9. public void doget (HttpServletRequest request, httpservletresponse response)
  10. Throws Servletexception, IOException {
  11. Response.setcontenttype ("text/html");
  12. SYSTEM.OUT.PRINTLN ("put message");
  13. PrintWriter out = Response.getwriter ();
  14. Out.flush ();
  15. String msg = request.getparameter ("message");
  16. if (null! = msg) {
  17. Messagelist.getinstance (). Add (msg);
  18. } else {
  19. SYSTEM.OUT.PRINTLN ("Add message:" + msg + "results");
  20. }
  21. Out.close ();
  22. }
  23. public void DoPost (HttpServletRequest request, httpservletresponse response)
  24. Throws Servletexception, IOException {
  25. Doget (request, response);
  26. }
  27. }

Here is the message queue that holds the message, which is used internally with a blocking queue

View Plaincopy to Clipboardprint?
  1. Package Hyjc.listener;
  2. Import Java.util.Iterator;
  3. Import Java.util.concurrent.LinkedBlockingQueue;
  4. public class Messagelist {
  5. private static Messagelist list = null;
  6. private static Object key = new Object ();
  7. Private Messagelist () {
  8. This.add ("Hello");
  9. This.add ("World");
  10. }
  11. public static Messagelist getinstance () {
  12. Synchronized (key) {
  13. if (list = = null) {
  14. List = new Messagelist ();
  15. }
  16. return list;
  17. }
  18. }
  19. Private Linkedblockingqueue queue = new Linkedblockingqueue ();
  20. public Boolean isEmpty () {
  21. return Queue.isempty ();
  22. }
  23. public int size () {
  24. return Queue.size ();
  25. }
  26. Public String get () {
  27. try {
  28. return Queue.take ();
  29. } catch (Interruptedexception e) {
  30. E.printstacktrace ();
  31. return null;
  32. }
  33. }
  34. public void Clear () {
  35. Queue.clear ();
  36. }
  37. public void Add (String msg) {
  38. try {
  39. Queue.put (msg);
  40. } catch (Interruptedexception e) {
  41. E.printstacktrace ();
  42. }
  43. }
  44. Public Iterator Iterator () {
  45. return Queue.iterator ();
  46. }
  47. }

Here is the demo effect, enter a message, click Submit, add to Messagelist, and then continue execution in getmsg for a long connection

Ajax-based long polling (long-polling) method for simple chat room programs

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.