springboot使用webSocket的兩種方式

han1396735592發表於2019-01-03
  • 方法一 使用 @ServerEndpoint 註解方式

  1. 新增 ServerEndpointExporter IOC 容器中

  2. ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
    }

  3. 使用@ServerEndpoint

package cn.qqhxj;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author han xinjian
 * @date 2018-11-20 17:29
 **/
@Component
@Slf4j
@ServerEndpoint(value = "/socket")
public class SocketHandler {
    private static CopyOnWriteArraySet<SocketHandler> webSocketSet
            = new CopyOnWriteArraySet<SocketHandler>();

    private Session session;

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
    }


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        log.info("歡迎id={}你的加入成功" , session.getId());
    }

    public void sendMessage(String string) throws IOException {
        this.session.getBasicRemote().sendText(JSONObject.toJSONString(string));
        //this.session.getAsyncRemote().sendText(message);
    }

   

    public static <T> void sendMessageToAll(String str) throws IOException {
        for (SocketHandler  item : webSocketSet) {
            try {
                item.sendMessage(str);
            } catch (IOException e) {
                continue;
            }
        }
    }
}
 

  • 方法二 繼承TextWebSocketHandler

  1. 配置

@Configuration
  1. class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

       registry.addEndpoint("/api/v1/socket")
               //新增允許跨域訪問
               .setAllowedOrigins("*")
               .withSockJS();

    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {

       //推送訊息字首
       registry.enableSimpleBroker("/api/v1/socket/send");
       //應用請求字首
       registry.setApplicationDestinationPrefixes("/api/v1/socket/req");
       //推送使用者字首
       registry.setUserDestinationPrefix("/user");

    }

    }

    
    2. ###  繼承`TextWebSocketHandler`
package cn.qqhxj.wsn.modules.wsn.socket;

import lombok.extern.slf4j.Slf4j;
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.util.concurrent.CopyOnWriteArraySet;

/**
* @author han xinjian
* @date 2018-12-26 13:06
**/
@Slf4j
@Component
public class BaseWebSocketHandler extends TextWebSocketHandler {


   private static CopyOnWriteArraySet<WebSocketSession> socketSessions = new CopyOnWriteArraySet<>();


   @Override
   public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
       socketSessions.add(session);
   }

   @Override
   public void afterConnectionEstablished(WebSocketSession session) throws Exception {
       socketSessions.remove(session);
   }

   @Override
   protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
       System.out.println(message.getPayload());
   }
}


相關文章