(转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 应用不同之处在于:
- 服务器端会阻塞请求直到有数据传递或超时才返回。
- 客户端 JavaScript 响应处理函数会在处理完服务器返回的信息后,再次发出请求,重新建立连接。
- 当客户端处理接收的数据、重新建立连接时,服务器端可能有新的数据到达;这些信息会被服务器端保存直到客户端重新建立连接,客户端会一次把当前服务器端所有的信息取回。
聊天页面的代码:
view plain
copy to clipboard
print
?
- <%@pagelanguage="java"pageEncoding="GBK"%>
- <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
- <html>
- <head>
- <title>chatroom</title>
- <metahttp-equiv="pragma"content="no-cache">
- <metahttp-equiv="cache-control"content="no-cache">
- <metahttp-equiv="expires"content="0">
- <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
- <metahttp-equiv="description"content="Thisismypage">
- <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>
- <mce:scripttype="text/javascript"src="ext-2.2/ext-all.js"mce_src="ext-2.2/ext-all.js"></mce:script>
- <mce:scripttype="text/javascript"
- src="ext-2.2/build/locale/ext-lang-zh_CN.js"></mce:script>
- <mce:scripttype="text/javascript"src="jslib/mm.js"mce_src="jslib/mm.js"></mce:script>
- </head>
- <body>
- <divid="main"></div><!--显示聊天记录的区域-->
- username:
- <inputtype="text"name="username"/>
- <br>
- message:
- <inputtype="text"id="message">
- <br>
- <inputtype="button"value="submit"onclick="putMsg()">
- </body>
- </html>
定义mm.js,定义发送消息,定义接收消息的JS函数
view plain
copy to clipboard
print
?
- Ext.onReady(function(){
- getMsg();
- });
- functiongetMsg(){
- Ext.Ajax.request({url:"getMsg",callback:function(options,success,response){
- if(success){
- Ext.DomHelper.append(Ext.get("main"),response.responseText,true);
- }
- getMsg();
- }});
- }
- functionputMsg(){
- Ext.Ajax.request({url:"putMsg",params:{message:document.getElementById("message").value}});
- }
- /*
- Ext.Updater.defaults.indicatorText='<div><imgsrc="icon/loading.gif"mce_src="icon/loading.gif"width="20"height="20"/>refresh...</div>';
- varupdater=Ext.get('main').getUpdater();
- updater.update({
- url:"getMsg"
- });
- */
下面是获得message的servlet
view plain
copy to clipboard
print
?
- packagehyjc.listener;
- importjava.io.IOException;
- importjava.io.PrintWriter;
- importjavax.servlet.ServletException;
- importjavax.servlet.http.HttpServlet;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- publicclassGetMsgextendsHttpServlet{
- publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
- throwsServletException,IOException{
- response.setContentType("text/html");
- PrintWriterout=response.getWriter();
- MessageListm=MessageList.getInstance();
- booleanend=false;
- while(!end){
- System.out.println("beforeget");
- Stringmsg=m.get();
- System.out.println("afterget"+msg);
- out.write(msg+"<br>");
- if(m.isEmpty()){
- end=true;
- }
- }
- out.close();
- }
- publicvoiddoPost(HttpServletRequestrequest,IOException{
- doGet(request,response);
- }
- }
下面是添加消息的servlet
view plain
copy to clipboard
print
?
- packagehyjc.listener;
- importjava.io.IOException;
- importjava.io.PrintWriter;
- importjavax.servlet.ServletException;
- importjavax.servlet.http.HttpServlet;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- publicclassPutMsgextendsHttpServlet{
- publicvoiddoGet(HttpServletRequestrequest,IOException{
- response.setContentType("text/html");
- System.out.println("putmessage");
- PrintWriterout=response.getWriter();
- out.flush();
- Stringmsg=request.getParameter("message");
- if(null!=msg){
- MessageList.getInstance().add(msg);
- }else{
- System.out.println("添加消息:"+msg+"成果");
- }
- out.close();
- }
- publicvoiddoPost(HttpServletRequestrequest,sans-serif"> 下面是存放消息的消息队列,内部用阻塞队列使用
view plain
copy to clipboard
print
?
- packagehyjc.listener;
- importjava.util.Iterator;
- importjava.util.concurrent.LinkedBlockingQueue;
- publicclassMessageList{
- privatestaticMessageListlist=null;
- privatestaticObjectkey=newObject();
- privateMessageList(){
- this.add("hello");
- this.add("world");
- }
- publicstaticMessageListgetInstance(){
- synchronized(key){
- if(list==null){
- list=newMessageList();
- }
- returnlist;
- }
- }
- privateLinkedBlockingQueue<String>queue=newLinkedBlockingQueue<String>();
- publicbooleanisEmpty(){
- returnqueue.isEmpty();
- }
- publicintsize(){
- returnqueue.size();
- }
- publicStringget(){
- try{
- returnqueue.take();
- }catch(InterruptedExceptione){
- e.printStackTrace();
- returnnull;
- }
- }
- publicvoidclear(){
- queue.clear();
- }
- publicvoidadd(Stringmsg){
- try{
- queue.put(msg);
- }catch(InterruptedExceptione){
- e.printStackTrace();
- }
- }
- publicIterator<String>iterator(){
- returnqueue.iterator();
- }
- }
下面是演示效果,输入message,点击submit,就会添加到MessageList中,然后会在GetMsg中继续执行,实现长连接
其它相关文章
http://yiminghe.javaeye.com/blog/284953
http://yiminghe.javaeye.com/blog/294781
http://yiminghe.javaeye.com/blog/300050 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|