pom
org.springframework.boot spring-boot-starter-websocket
ServerEndpointExporter
@Configuration
@EnableWebSocket
@Service
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
工具类
package com.plus.config.message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/websocket/{user}")
public class MyWebSocket {
private static final Logger logger = LoggerFactory.getLogger(MyWebSocket.class);
public static Map clients = new ConcurrentHashMap();
@onOpen
public void onOpen(@PathParam("user") String myWebsocket, Session session) {
logger.info("进入:++++++++++++++++++++++++++++++++" + myWebsocket);
clients.put(myWebsocket, session);
// BROADCAST(myWebsocket+"上线了");
}
@onMessage
public void onMessage(@PathParam("user") String myWebsocket, String message, Session session) {
System.out.println(message);
if(null==clients.get(myWebsocket)) {
clients.put(myWebsocket, session);
}
}
@onError
public void onError(@PathParam("user") String myWebsocket, Throwable throwable) {
try {
BROADCAST(myWebsocket,"keep");
}catch(Exception e) {
clients.remove(myWebsocket);
}
}
@onClose
public void onClose(@PathParam("user") String myWebsocket) {
System.out.println("websoket关闭:" + myWebsocket);
clients.remove(myWebsocket);
}
public static void BROADCAST(String myWebsocket, String message) {
try {
if (clients.containsKey(myWebsocket)) {
clients.get(myWebsocket).getAsyncRemote().sendText(message);
} else {
logger.info("websocket未找到" + myWebsocket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void BROADCAST(String message) throws IOException {
Collection values = clients.values();
for (Session s:values) {
if(s!=null){
s.getBasicRemote().sendText(message);
}else {
System.out.println("用户不存在");
}
}
}
}



