方法一 使用
@ServerEndpoint
注解方式
添加
ServerEndpointExporter
到IOC
容器中ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}使用
@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
配置
@Configuration
-
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());
}
}