基于Tomcat7的WebSocket的程序

lxrj00 2013-07-21

             在开始学习GUI的SOCKET编程时,就一直有一个梦想,希望有一天能将这种聊天程序在WEB上实现,虽然QQ和许多其它的聊天程序已经实现,但是他们的实现都使用的是AJAX,无非是对AJAX进行改进,或者使用FLEX,个人认为那样实现太复杂,没有研究!!几个星期前终天有时间研究了,使用jetty来编写聊天程序,后来聊天都实现了,但是jetty服务器没有使用过,中间配服务器差不多用了一个星期,让我很纠结,最后在实验室的电脑可以成功运行!!!不过可悲的是当我移植到我的笔记本时,却出现在了各种怪错!!于是,我又纠结了,今天晚上,奇迹的发现tomcat竟然也支持了,所以果然的下载了tomcat7.0.27来测试,惊人的发现与jetty实现相似,所以写了一个小测试程序,测试成功!!下面贴上我的代码,有兴趣的童鞋可以一起学习哦!!!! 
index.jsp 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
    String path = request.getContextPath(); 
    String basePath = request.getScheme() + "://" 
            + request.getServerName() + ":" + request.getServerPort() 
            + path + "/"; 
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>"> 

<title>My JSP 'index.jsp' starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="This is my page"> 
<script type="text/javascript"> 
    var ws = null; 
    function startServer() { 
        var url = "ws:localhost:8080/WebSocketAnnonationTomcat7/echo.ws"; 
        if ('WebSocket' in window) { 
            ws = new WebSocket(url); 
        } else if ('MozWebSocket' in window) { 
            ws = new MozWebSocket(url); 
        } else { 
            alert('WebSocket is not supported by this browser.'); 
            return; 
        } 
        ws.onopen = function() { 
            alert("connect success!"); 
        }; 
        ws.onmessage = function(event) { 
            alert("revice mess:" + event.data); 
        }; 
        ws.onclose = function() { 
            alert("close connect.."); 
        }; 
    } 
    function sendMessage(){
         var txtMsg=document.getElementById("msg").value;
         if(ws!=null && txtMsg!=''){
             ws.send(txtMsg);
         }
         
        }
</script> 
</head> 

<body onload="startServer()"> 
  <input type="text" id="msg" value="" size="20" />
  <input type="button" onclick="sendMessage();" value="发送" />
</body> 
</html>

servlet具体实现:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.logging.Logger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WsOutbound;

/**
 * Tomcat7 WebSocket的簡單應用, WebSocket的servlet接口集成自webSocketServlet,实质为Serlet
 * <p>功能描述,该部分必须以中文句号结尾。<p>
 *
 * 创建日期  2013-7-21<br>
 * @author  longgangbai <br>
 * @version $Revision$ $Date$
 * @since   3.0.0
 */
public class WebSocketExtServlet extends 
        org.apache.catalina.websocket.WebSocketServlet { 
    //
    private Logger logger=Logger.getLogger(WebSocketExtServlet.class.getSimpleName());
    
    private static final long serialVersionUID = 1L;

    
    @Override
    protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest arg1) {
        logger.info(";request ws servelt");
        
        return  new MessageInbound(){
            @Override
            protected void onClose(int status){
                logger.info(";web socket closed :"+status);
            }
            @Override
            protected void onOpen(WsOutbound outbound){
                logger.info(";web socket onOpen !");
            }
            @Override
            protected void onBinaryMessage(ByteBuffer buff) throws IOException {
                // TODO Auto-generated method stub
                logger.info(";web socket Received : !"+buff.remaining());
            }

            @Override
            protected void onTextMessage(CharBuffer buff) throws IOException {
                logger.info(";web socket Received : !"+buff.remaining());
                //getWsOutbound可以返回当前的WsOutbound,通过他向客户端返回数据,这里采用nio的CharBuffer
                for (int j = 0; j < 50; j++) {
                    try {
                        Thread.sleep(2000);
                        this.getWsOutbound().writeTextMessage(CharBuffer.wrap(String.valueOf(j)));
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
            }
            
        }; 
    } 

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>WebSocketTomcat7</display-name>
  <servlet>
   <servlet-name>websocket</servlet-name>
   <servlet-class>com.easyway.websocket.WebSocketExtServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>websocket</servlet-name>
     <url-pattern>/echo.ws</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 
需要说明的是,在开发的时候必须在tomcat的lib目录下拷贝两个JAR包:catalina.jar  tomcat-coyote.jar 
但当你运行的时候必须将这两个包删除,否则,会与tomcat的包冲突!!!!! 
他们类的关系,也有一定的理解,今天暂时写到这里吧!! 

相关推荐