webSocket 案例 原生使用servlet

原生使用servlet创建WebSocket案例
注意问题:
                1、在网上的案例中 一般会引入两个jar包  catalina.jar, websocket-api.jar 两个jar包但是在项目启动时会出现报错信息所以我做的如下案例将catalina.jar去掉了
                2、 catalina.jar, websocket-api.jar 其实这两个jar包在tomcat7.0.68中是存在的 所以在运行项目于时一定要引入tomcat中的jar文件否则项目就会报错,原因就是这两个jar对tomcat中其他的jar有依赖关        系,在项目启动时 就会找不到相关的jar
                
所以推测一下 在网上有一种说法是 在使用tomcat时要查看版本说是tomcat7.0以上 但是如果是以上的方法 可以尝试一下 不一定适用tomcat7.0以上 导入相关的jar包 应该也能实现 我就没有尝试 太懒了 ~
其实  catalina.jar, websocket-api.jar 直接引入tomcat中也能使用 上面的就是记录一下 项目中遇到的问题 。留着以后发现问题。
servlet端
package com.webscoletdemo.action;
import  java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceFeature;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

public class WebScoketAction extends WebSocketServlet {  
    private static final long serialVersionUID = -4853540828121130946L;  
    private static List<MyMessageInbound> mmiList = new ArrayList<MyMessageInbound>();  

    @Override  
    protected MyMessageInbound createWebSocketInbound(String str,  
            HttpServletRequest request) {  
        request.getParameter("");       
        return new MyMessageInbound();  
    }  

    private class MyMessageInbound extends MessageInbound {  
        WsOutbound myoutbound;  
        //开启websocket
        public void onOpen(WsOutbound outbound) {  
            try {  
                System.out.println("Open Client.");  
                this.myoutbound = outbound;  
                mmiList.add(this);  
                outbound.writeTextMessage(CharBuffer.wrap("Hello!"));  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  

        //关闭websocket
        public void onClose(int status) {  
            System.out.println("Close Client.");  
            mmiList.remove(this);  
        }  
       //当服务器端收到信息的时候,就对所有的连接进行遍历并且把收到的信息发送给所有用户  
        public void onTextMessage(CharBuffer cb) throws IOException {  
            System.out.println("Accept Message : " + cb);  
            for (MyMessageInbound mmib : mmiList) {  
                CharBuffer buffer = CharBuffer.wrap(cb);  
                mmib.myoutbound.writeTextMessage(buffer);  
                mmib.myoutbound.flush();  
            }  
        }  


        public void onBinaryMessage(ByteBuffer bb) throws IOException {  

        }  
    }  
}  
index.jsp 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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
var socket = new WebSocket("ws://localhost:8080/WebSocketDemo/aa.do?aaa=11");
socket.onopen = function(){
    //浏览器socket开始进入
    console.log("open");
    //向服务器端发送信息
    socket.send("open+hello");
};
socket.onmessage = function(evt)
{
    console.log("message");
    console.log("onmessage:"+evt.data);
};
socket.onclose = function(evt){
    console.log("close");
    console.log("onclose:"+evt.data);
};
socket.onerror = function(evt)
{
    console.log("error");
    console.log("onerror:"+evt.data);
};
function send()
{
    //socket.send("sendMessage");
}
function closeWebSocket(){
     socket.close();
}

</script>
  </head>

  <body>
    This is my JSP page. <br>
     Welcome<br/>
   <button οnclick="send()">Send</button>    <button οnclick="closeWebSocket()">Close</button>
    <div id="message">
    </div>
  </body>
</html>


web.xml 端
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee 
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>aa</servlet-name>
    <servlet-class>com.webscoletdemo.action.WebScoketAction</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>aa</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

lib: websocket-api.jar

版权声明:本文为zy846771221原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。