用tomcat8实现websocket

2016-05-17  本文已影响2417人  else05

这个最好是tomcat 8+ ,前端主要借用html5的websocket , 在tomcat中有demo,可以启动tomcat(8+,以前的旧版本不支持websocket

GIF.gif Paste_Image.png
服务器返回的信息:
<input type="text" id="show"/>

浏览器发送的信息:
<input type="text" id="msg"/>
<input type="button" value="send" id="send"/>

<script src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    var w = null ;
    if('WebSocket' in window){
        w = new WebSocket('ws://localhost:8080/WebsocketByAnnotation') ;
    }else {
        console.warn('不支持websocket') ;
    }

    w.onopen = function(obj){
        console.info('open') ;
        console.info(obj) ;
    } ;
    w.onmessage = function(obj){
// 这里接收服务器返回的信息
        console.info('msg') ;
        $('#show').val(obj.data) ;
    } ;
    w.onclose = function (obj) {
        console.info('close') ;
        console.info(obj) ;
    } ;


    $('#send').click(function(){
        var msg = $('#msg').val() ;
        w.send(msg) ;
    }) ;

</script>
// 配置websocket
public class WebScoketConf implements ServerApplicationConfig {
    @Override
    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> set) {
        return null;
    }

    @Override
    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> set) {
    // 使用注解则要使用这个方法进行配置,可以在这里下断点看set里面有什么内容
        return set;
    }
}
// 这个类启动后不是单例,每增加一个websocket连接就会有新的实例
@ServerEndpoint("/WebsocketByAnnotation")
public class WebsocketByAnnotation {
    public WebsocketByAnnotation() {
        System.out.println("he");
    }

    @OnOpen
    public void open(Session session){
        System.out.println("open============sessionID:"+ session.getId());
    }

    @OnClose
    public void close(Session session){
        System.out.println("close============");
    }

    @OnMessage
    public void sendTex(Session session ,String msg , boolean last){
// 这里接收浏览器发过来的信息
        System.out.println("收到信息:" + msg);
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText("server回复"+msg,last);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
// TODO 这里的session不能关闭,否则websocket连接就会断开
//                session.close();
        }
    }
}
Paste_Image.png Paste_Image.png
上一篇下一篇

猜你喜欢

热点阅读