加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

基于AJAX的长轮询(long-polling)方式实现简单的聊天室程序

发布时间:2020-12-15 21:03:50 所属栏目:百科 来源:网络整理
导读:(转http://blog.csdn.net/neusoftware_20063500/archive/2009/04/30/4140903.aspx) 这里只是做个测试,很简单,没有做好线程同步的问题,只是为了长轮询。 原理: 可以看:http://yiminghe.javaeye.com/blog/294781 AJAX 的出现使得 JavaScript 可以调用 XM


(转http://blog.csdn.net/neusoftware_20063500/archive/2009/04/30/4140903.aspx)

这里只是做个测试,很简单,没有做好线程同步的问题,只是为了长轮询。

原理:

可以看:http://yiminghe.javaeye.com/blog/294781

AJAX 的出现使得 JavaScript 可以调用 XMLHttpRequest 对象发出 HTTP 请求,JavaScript 响应处理函数根据服务器返回的信息对 HTML 页面的显示进行更新。使用 AJAX 实现“服务器推”与传统的 AJAX 应用不同之处在于:

  1. 服务器端会阻塞请求直到有数据传递或超时才返回。
  2. 客户端 JavaScript 响应处理函数会在处理完服务器返回的信息后,再次发出请求,重新建立连接。
  3. 当客户端处理接收的数据、重新建立连接时,服务器端可能有新的数据到达;这些信息会被服务器端保存直到客户端重新建立连接,客户端会一次把当前服务器端所有的信息取回。

聊天页面的代码:

view plain copy to clipboard print ?
  1. <%@pagelanguage="java"pageEncoding="GBK"%>
  2. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  3. <html>
  4. <head>
  5. <title>chatroom</title>
  6. <metahttp-equiv="pragma"content="no-cache">
  7. <metahttp-equiv="cache-control"content="no-cache">
  8. <metahttp-equiv="expires"content="0">
  9. <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
  10. <metahttp-equiv="description"content="Thisismypage">
  11. <mce:scripttype="text/javascript"src="ext-2.2/adapter/ext/ext-base.js"mce_src="ext-2.2/adapter/ext/ext-base.js"></mce:script>
  12. <mce:scripttype="text/javascript"src="ext-2.2/ext-all.js"mce_src="ext-2.2/ext-all.js"></mce:script>
  13. <mce:scripttype="text/javascript"
  14. src="ext-2.2/build/locale/ext-lang-zh_CN.js"></mce:script>
  15. <mce:scripttype="text/javascript"src="jslib/mm.js"mce_src="jslib/mm.js"></mce:script>
  16. </head>
  17. <body>
  18. <divid="main"></div><!--显示聊天记录的区域-->
  19. username:
  20. <inputtype="text"name="username"/>
  21. <br>
  22. message:
  23. <inputtype="text"id="message">
  24. <br>
  25. <inputtype="button"value="submit"onclick="putMsg()">
  26. </body>
  27. </html>

定义mm.js,定义发送消息,定义接收消息的JS函数

view plain copy to clipboard print ?
  1. Ext.onReady(function(){
  2. getMsg();
  3. });
  4. functiongetMsg(){
  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. functionputMsg(){
  13. Ext.Ajax.request({url:"putMsg",params:{message:document.getElementById("message").value}});
  14. }
  15. /*
  16. Ext.Updater.defaults.indicatorText='<div><imgsrc="icon/loading.gif"mce_src="icon/loading.gif"width="20"height="20"/>refresh...</div>';
  17. varupdater=Ext.get('main').getUpdater();
  18. updater.update({
  19. url:"getMsg"
  20. });
  21. */

下面是获得message的servlet

view plain copy to clipboard print ?
  1. packagehyjc.listener;
  2. importjava.io.IOException;
  3. importjava.io.PrintWriter;
  4. importjavax.servlet.ServletException;
  5. importjavax.servlet.http.HttpServlet;
  6. importjavax.servlet.http.HttpServletRequest;
  7. importjavax.servlet.http.HttpServletResponse;
  8. publicclassGetMsgextendsHttpServlet{
  9. publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
  10. throwsServletException,IOException{
  11. response.setContentType("text/html");
  12. PrintWriterout=response.getWriter();
  13. MessageListm=MessageList.getInstance();
  14. booleanend=false;
  15. while(!end){
  16. System.out.println("beforeget");
  17. Stringmsg=m.get();
  18. System.out.println("afterget"+msg);
  19. out.write(msg+"<br>");
  20. if(m.isEmpty()){
  21. end=true;
  22. }
  23. }
  24. out.close();
  25. }
  26. publicvoiddoPost(HttpServletRequestrequest,IOException{
  27. doGet(request,response);
  28. }
  29. }

下面是添加消息的servlet

view plain copy to clipboard print ?
  1. packagehyjc.listener;
  2. importjava.io.IOException;
  3. importjava.io.PrintWriter;
  4. importjavax.servlet.ServletException;
  5. importjavax.servlet.http.HttpServlet;
  6. importjavax.servlet.http.HttpServletRequest;
  7. importjavax.servlet.http.HttpServletResponse;
  8. publicclassPutMsgextendsHttpServlet{
  9. publicvoiddoGet(HttpServletRequestrequest,IOException{
  10. response.setContentType("text/html");
  11. System.out.println("putmessage");
  12. PrintWriterout=response.getWriter();
  13. out.flush();
  14. Stringmsg=request.getParameter("message");
  15. if(null!=msg){
  16. MessageList.getInstance().add(msg);
  17. }else{
  18. System.out.println("添加消息:"+msg+"成果");
  19. }
  20. out.close();
  21. }
  22. publicvoiddoPost(HttpServletRequestrequest,sans-serif"> 下面是存放消息的消息队列,内部用阻塞队列使用

    view plain copy to clipboard print ?
    1. packagehyjc.listener;
    2. importjava.util.Iterator;
    3. importjava.util.concurrent.LinkedBlockingQueue;
    4. publicclassMessageList{
    5. privatestaticMessageListlist=null;
    6. privatestaticObjectkey=newObject();
    7. privateMessageList(){
    8. this.add("hello");
    9. this.add("world");
    10. }
    11. publicstaticMessageListgetInstance(){
    12. synchronized(key){
    13. if(list==null){
    14. list=newMessageList();
    15. }
    16. returnlist;
    17. }
    18. }
    19. privateLinkedBlockingQueue<String>queue=newLinkedBlockingQueue<String>();
    20. publicbooleanisEmpty(){
    21. returnqueue.isEmpty();
    22. }
    23. publicintsize(){
    24. returnqueue.size();
    25. }
    26. publicStringget(){
    27. try{
    28. returnqueue.take();
    29. }catch(InterruptedExceptione){
    30. e.printStackTrace();
    31. returnnull;
    32. }
    33. }
    34. publicvoidclear(){
    35. queue.clear();
    36. }
    37. publicvoidadd(Stringmsg){
    38. try{
    39. queue.put(msg);
    40. }catch(InterruptedExceptione){
    41. e.printStackTrace();
    42. }
    43. }
    44. publicIterator<String>iterator(){
    45. returnqueue.iterator();
    46. }
    47. }

    下面是演示效果,输入message,点击submit,就会添加到MessageList中,然后会在GetMsg中继续执行,实现长连接

    其它相关文章

    http://yiminghe.javaeye.com/blog/284953

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

    http://yiminghe.javaeye.com/blog/300050

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读