基于html5的WebSocket使用方式(承接jetty配置)

作者: admin 分类: 学习文档 发布时间: 2011-11-13 00:08

创建类:WebSearchServlet.java

Java代码
  1. package org.search.servlet;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.eclipse.jetty.websocket.WebSocket;
  4. import org.eclipse.jetty.websocket.WebSocketServlet;
  5. public class WebSearchServlet extends WebSocketServlet{
  6.     /**
  7.      *
  8.      */
  9.     private static final long serialVersionUID = 5136484809757218548L;
  10.     public WebSocket doWebSocketConnect(HttpServletRequest arg0, String arg1) {
  11.         return new SearchServlet();
  12.     }
  13. }

 

创建类:SearchServlet.java

Java代码
  1. package org.search.servlet;
  2. import org.eclipse.jetty.websocket.WebSocket;
  3. public class SearchServlet implements WebSocket{
  4.     public void onClose(int arg0, String arg1) {
  5.         System.out.println(“onClose”);
  6.     }
  7.     public void onOpen(final Connection conn) {
  8.         System.out.println(“onOpen”);
  9.          new Thread() {
  10.              @Override
  11.              public void run() {
  12.                  try {
  13.                      conn.sendMessage(“sdfsdf”);
  14.                      int i =0;
  15.                      while (true) {
  16.                          sleep(1000);
  17.                          conn.sendMessage(“Count:” + (i++));
  18.                      }
  19.                  } catch (final Exception e) {
  20.                      System.err.println(e.getMessage());
  21.                  }
  22.              }
  23.          }.start();
  24.     }
  25. }

 

在JSP目录下新建文件comet.html内容如下:

Java代码
  1. <html>
  2.     <head>
  3.         <title>WebSoket Demo</title>
  4.         <script type=”text/javascript”>
  5.             if (!window.WebSocket) {
  6.                 alert(“WebSocket not supported by this browser!”);
  7.             }
  8.             function display() {
  9.                 var valueLabel = document.getElementById(“valueLabel”);
  10.                 valueLabel.innerHTML = “”;
  11.                 var ws = new WebSocket(“ws://localhost:9999/comet.do”);
  12.                 ws.onmessage = function(evt) {
  13.                     valueLabel.innerHTML = evt.data;
  14.                 };
  15.                 ws.onclose = function() {
  16.                 };
  17.                 ws.onopen = function() {
  18.                     ws.send(“Hello, Server!”);
  19.                 };
  20.             }
  21.         </script>
  22.     </head>
  23.     <body onload=”display();”>
  24.         <div id=”valueLabel”></div>
  25.     </body>
  26. </html>

 

运行jetty.访问地址http://localhost:9999/comet.html效果如下:

 

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Protected by WP Anti Spam