tomcat7和tomcat8的websocket区别

来源:互联网 发布:迅龙数据恢复免费版 编辑:程序博客网 时间:2024/05/17 06:14

tomcat8真正支持jsr-356(包含对websocket的支持), tomcat7部分版本的websocket实现不兼容jsr-356。websocket实现tomcat7.x与tomcat8.x有很大差异。在tomcat7中使用websocket需要定义一个servlet,然后继承WebSocketServlet,在tomcat8中使用websocke。出自:http://blog.csdn.net/liuxiao723846/article/details/46930173


一、tomcat7定义servlet的方式简单举例。

1、新建一个环境为tomcat7的web工程,需要的包有catalina.jar,tomcat-coyote.jar。

2、修改web.xml。

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:web="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee"id="WebApp_ID" version="2.5">  <servlet><servlet-name>WebSocket</servlet-name><servlet-class>Tomcat7Test</servlet-class></servlet><servlet-mapping><servlet-name>WebSocket</servlet-name><url-pattern>/websocket/*</url-pattern></servlet-mapping>   </web-app>

3、写一个后台类:Tomcat7Test.java。

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 org.apache.catalina.websocket.MessageInbound;import org.apache.catalina.websocket.StreamInbound;import org.apache.catalina.websocket.WebSocketServlet;import org.apache.catalina.websocket.WsOutbound;public class Tomcat7Test extends WebSocketServlet{@Overrideprotected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) {// TODO Auto-generated method stubreturn new MsgInbound();}private class MsgInbound extends MessageInbound{protected void onClose(int status){              super.onClose(status);          }          protected void onOpen(WsOutbound outbound){              super.onOpen(outbound);          }          @Overrideprotected void onBinaryMessage(ByteBuffer arg0) throws IOException {// TODO Auto-generated method stub}@Overrideprotected void onTextMessage(CharBuffer message) throws IOException {// TODO Auto-generated method stubSystem.out.println(message.toString());//将websocket传过来的值返回回去WsOutbound outbound=this.getWsOutbound();outbound.writeTextMessage(message);outbound.flush();}}}

4、前端html页面。
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body>服务器返回的信息:<input type="text" id="show"/>浏览器发送的信息:<input type="text" id="msg"/><input type="button" value="send" id="send" onclick="q()"/><script>    var ws = null ;    var target="ws://localhost:8080/TestWeb/websocket/test";    if ('WebSocket' in window) {        ws = new WebSocket(target);    } else if ('MozWebSocket' in window) {        ws = new MozWebSocket(target);    } else {        alert('WebSocket is not supported by this browser.');    }    ws.onopen = function(obj){        console.info('open') ;        console.info(obj) ;    } ;        ws.onclose = function (obj) {        console.info('close') ;        console.info(obj) ;    } ;    ws.onmessage = function(obj){        console.info(obj) ;        document.getElementById('show').value=obj.data;    } ;    function q(){    ws.send(document.getElementById('msg').value);    }</script></body></html>

二、tomcat8使用websocket实例。

只需要写java类,和前端代码。

1、新建一个环境为tomcat7的web工程,需要的包有websocket-api.jar

2、后台java类。

import java.io.IOException;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;//一定要添加这个注释@ServerEndpoint("/websocket/test")public class Test {@OnOpenpublic void onOpen(){System.out.println("WEBopen");}@OnClosepublic void onClose(){System.out.println("WEBCLOSE");}@OnMessagepublic void onMessage(Session session,String msg){System.out.println("send message"+msg);if(session.isOpen()){try {//将websocket传过来的值返回回去session.getBasicRemote().sendText(msg);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
3、前端html代码。

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body>服务器返回的信息:<input type="text" id="show"/>浏览器发送的信息:<input type="text" id="msg"/><input type="button" value="send" id="send" onclick="q()"/><script>    var ws = null ;    var target="ws://localhost:8080/TestWeb/websocket/test";    if ('WebSocket' in window) {        ws = new WebSocket(target);    } else if ('MozWebSocket' in window) {        ws = new MozWebSocket(target);    } else {        alert('WebSocket is not supported by this browser.');    }    ws.onopen = function(obj){        console.info('open') ;        console.info(obj) ;    } ;        ws.onclose = function (obj) {        console.info('close') ;        console.info(obj) ;    } ;    ws.onmessage = function(obj){        console.info(obj) ;        document.getElementById('show').value=obj.data;    } ;    function q(){    ws.send(document.getElementById('msg').value);    }</script></body></html>
三、备注:

1、websocket的前端代码都是一样的。

2、tomcat7也支持上述的非servlet方式。

3、tomcat8不支持servlet,没有对应要继承的WebSocketServlet.java。

4、注意不要发生包冲突问题。

1)web项目里面不能有跟tomcat/lib一样的包,否则启动tomcat的时候会发生包冲突。

2)在tomcat的contex.xml中添加<Loader delegate="true"/>(不建议使用,容易产生其他错误)

作用: Loader对象可出现在Context中以控制Java类的加载。

属性:delegate、含义:True代表使用正式的Java代理模式(先询问父类的加载器);false代表先在Web应用程序中寻找。默认值:FALSE。

5、以上的列子在tomcat的examples里面都有,需要学习可以直接在里面看源码。