一区二区三区日韩精品-日韩经典一区二区三区-五月激情综合丁香婷婷-欧美精品中文字幕专区

分享

springboot 中使用websocket簡單例子

 LZS2851 2017-06-02

gradle 中添加依賴,引入websocket支持

    compile("org.springframework.boot:spring-boot-starter-websocket:${springBootVersion}")

啟用websocket

復(fù)制代碼
package cn.xiaojf.today.ws.configuration;

import cn.xiaojf.today.ws.handler.CountWebSocketHandler;
import cn.xiaojf.today.ws.interceptor.HandshakeInterceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket 配置
 * @author xiaojf 2017/3/2 9:50.
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(ApplicationContext context) {
        return new ServerEndpointExporter();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new CountWebSocketHandler(), "/web/count").addInterceptors(new HandshakeInterceptor());
    }
}
復(fù)制代碼

消息攔截處理

復(fù)制代碼
package cn.xiaojf.today.ws.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * 消息攔截處理類
 * @author xiaojf 2017/3/2 10:36.
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {

        //解決The extension [x-webkit-deflate-frame] is not supported問題
        if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
            request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
        }

        System.out.println("Before Handshake");
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {

        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
復(fù)制代碼

消息處理相應(yīng)類

復(fù)制代碼
package cn.xiaojf.today.ws.handler;

import com.alibaba.druid.support.json.JSONUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;

/**
 * @author xiaojf 2017/3/2 9:55.
 */
@Component
public class CountWebSocketHandler extends TextWebSocketHandler {
    private static long count = 0;
    private static Map<String,WebSocketSession> sessionMap = new HashedMap();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        session.sendMessage(new TextMessage(session.getPrincipal().getName()+",你是第" + (sessionMap.size()) + "位訪客")); //p2p

        Object parse = JSONUtils.parse(message.getPayload());

        Collection<WebSocketSession> sessions = sessionMap.values();
        for (WebSocketSession ws : sessions) {//廣播
            ws.sendMessage(message);
        }

        sendMessage(sessionMap.keySet(),"你好");
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessionMap.put(session.getPrincipal().getName(),session);
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessionMap.remove(session.getPrincipal().getName());
        super.afterConnectionClosed(session, status);
    }

    /**
     * 發(fā)送消息
     * @author xiaojf 2017/3/2 11:43
     */
    public static void sendMessage(String username,String message) throws IOException {
        sendMessage(Arrays.asList(username),Arrays.asList(message));
    }

    /**
     * 發(fā)送消息
     * @author xiaojf 2017/3/2 11:43
     */
    public static void sendMessage(Collection<String> acceptorList,String message) throws IOException {
        sendMessage(acceptorList,Arrays.asList(message));
    }

    /**
     * 發(fā)送消息,p2p 群發(fā)都支持
     * @author xiaojf 2017/3/2 11:43
     */
    public static void sendMessage(Collection<String> acceptorList, Collection<String> msgList) throws IOException {
        if (acceptorList != null && msgList != null) {
            for (String acceptor : acceptorList) {
                WebSocketSession session = sessionMap.get(acceptor);
                if (session != null) {
                    for (String msg : msgList) {
                        session.sendMessage(new TextMessage(msg.getBytes()));
                    }
                }
            }
        }
    }
}
復(fù)制代碼

前端js,需要依賴jquery

復(fù)制代碼
require(["jquery","formUtil"], function ($) {

    var url = 'ws://'+window.location.host+'/web/count';
    var ws = new WebSocket(url);
    ws.onopen = function(e)
    {
        // ws.send('hello');
    };

    ws.onmessage = function(e) {
        alert(e.data);
    };

    ws.onerror = function(e) {
        alert(e);
    };

    $('body').one('DOMNodeRemoved','#start-help',function (e) {//執(zhí)行一次以后,自動銷毀監(jiān)聽事件
        ws.close();
    });

    $('#help-submit').on('click',function () {
        var formData = $('#help-form').serializeJson();
        ws.send(JSON.stringify(formData));
    }) ;

});
復(fù)制代碼

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多

    亚洲综合天堂一二三区| 欧美日韩在线第一页日韩| 五月天丁香婷婷狠狠爱| 日本午夜免费观看视频| 国产原创中文av在线播放| 国产欧美一区二区久久| 在线日本不卡一区二区| 中文字幕日韩欧美一区| 久久精品亚洲精品国产欧美| 亚洲av熟女一区二区三区蜜桃 | 国产一区二区不卡在线视频| 国产一区日韩二区欧美| 综合久综合久综合久久| 欧美性猛交内射老熟妇| 97人妻精品免费一区二区| 欧美日韩一区二区综合| 成人精品一区二区三区综合 | 日本少妇中文字幕不卡视频| 亚洲一区二区精品久久av| 亚洲男人天堂成人在线视频| 日本精品视频一二三区| 亚洲黄色在线观看免费高清| 欧美综合色婷婷欧美激情| 91欧美日韩国产在线观看| 欧美日韩国产欧美日韩| 精品国产日韩一区三区| 久久久精品区二区三区| 伊人久久五月天综合网| 亚洲第一视频少妇人妻系列| 日韩欧美中文字幕人妻| 在线精品首页中文字幕亚洲| 国产专区亚洲专区久久| 人妻久久一区二区三区精品99| 好吊色欧美一区二区三区顽频| 日韩女优视频国产一区| 欧美亚洲国产日韩一区二区| 91精品国产av一区二区| 亚洲天堂精品1024| 免费在线播放不卡视频| 午夜传媒视频免费在线观看| 久久这里只精品免费福利|