用tomcat8實現websocket

這個最好是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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容