91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring boot + Websocket

發布時間:2020-06-11 13:01:05 來源:網絡 閱讀:820 作者:libing111 欄目:開發技術

1、添加配置類


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
     /**
     * 注入ServerEndpointExporter,
     * 這個bean會自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

2、添加WebSocket類

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{shopId}")
public class WebSocket {
    private static Logger logger = LoggerFactory.getLogger(WebSocket.class);

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "shopId") String shopId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(shopId, session);
        logger.info("有新的連接,總數為:{}", webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("連接斷開,總數為:{}", webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        logger.info("收到客戶端消息:{}", message);
    }

    // 此為廣播消息
    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】廣播消息:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }

    // 此為單點消息
    public void sendOneMessage(String shopId, String message) {
        Session session = sessionPool.get(shopId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }

}

3、添加測試類

import com.sgcc.gtfsamservice.componet.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api")
public class TestController {
    @Autowired
    private WebSocket webSocket;

    @RequestMapping("/sendAllWebSocket")
    public String test() {    
        webSocket.sendAllMessage("hello");
        return "多發!";        
    }

    @RequestMapping("/sendOneWebSocket")
    public String sendOneWebSocket() {
        webSocket.sendOneMessage("channel001", "hello!");
        return "單發";
    }
}

4、前端Vue

export default {
    name: 'relationship',
    data () {
      return {

      }
    },
    created () { // 頁面創建生命周期函數
      this.initWebSocket()
    },
    destroyed: function () { // 離開頁面生命周期函數
      this.websocketclose()
    },
    methods: {
      initWebSocket: function () {
        // ws等同http,wss等同https,其中ip為后端應用主機,port為后端啟動所占用的端口
        this.websock = new WebSocket('ws://ip:port/websocket/channel001')
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onmessage = this.websocketonmessage
        this.websock.onclose = this.websocketclose
      },
      websocketonopen: function () {
        console.log('WebSocket連接成功')
      },
      websocketonerror: function (e) {
        console.log('WebSocket連接發生錯誤')
      },
      websocketonmessage: function (e) {
        var da = JSON.parse(e.data)
        console.log(da)
        this.message = da
      },
      websocketclose: function (e) {
        console.log('connection closed (' + e.code + ')')
      },
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

望奎县| 浦江县| 都江堰市| 霍林郭勒市| 阳信县| 勐海县| 新源县| 民勤县| 普宁市| 辽源市| 沿河| 淮阳县| 历史| 茌平县| 紫金县| 吉木乃县| 郓城县| 东莞市| 施甸县| 博罗县| 张掖市| 安塞县| 调兵山市| 大丰市| 资兴市| 廉江市| 雷波县| 修武县| 平原县| 永善县| 竹山县| 邯郸市| 山丹县| 乌拉特中旗| 长子县| 富平县| 崇明县| 昭通市| 股票| 汤阴县| 莎车县|