1. 依赖
<!-- SpringBoot WebSocket -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 自动注册配置类
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** @return*/@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
3. WebSocket服务类
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.concurrent.CopyOnWriteArraySet;/*** postman访问: ws://localhost:8080/ws/{userId}* 浏览器访问: http://localhost:8080/ws*/
@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {private static int onlineCount = 0;private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();private Session session;private String userId = "";@OnOpenpublic void onOpen(Session session, @PathParam("userId") String userId) {this.session = session;webSocketSet.add(this); //加入set中addOnlineCount(); //在线数加1this.userId = userId;sendMessage(userId + "用户" + ", 连接成功 !");System.out.println("【websocket】 " + userId + "用户" + "已连接!当前在线人数为" + getOnlineCount());}@OnClosepublic void onClose() {webSocketSet.remove(this); //从set中删除subOnlineCount(); //在线数减1System.out.println("【websocket】 " + userId + "用户" + "已关闭!当前在线人数为" + getOnlineCount());}@OnMessagepublic void onMessage(String message, Session session) {if(message.startsWith("target-")){int index = message.indexOf(":");String userId = message.substring(7,index);sendInfo(message.substring(index + 1), userId);return;}this.session = session;sendMessage("【websocket】 服务端收到来自窗口" + userId + "发送的消息:" + message);}@OnErrorpublic void onError(Session session, Throwable error) {this.session = session;error.printStackTrace();}private void sendMessage(String message) {try {this.session.getBasicRemote().sendText(message);} catch (IOException e) {e.printStackTrace();}}// 群发消息/*** 群发自定义消息*/public static void sendInfo(String message, @PathParam("userId") String userId) {System.out.println("【websocket】 推送消息给" + userId + "用户" + ",推送内容:" + message);for (WebSocketServer item : webSocketSet) {//这里可以设定只推送给这个userId的,为null则全部推送if (userId == null) {
// item.sendMessage(message);} else if (item.userId.equals(userId)) {item.sendMessage(message);}}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {return webSocketSet;}
}
4. 模拟通信
【websocket】 2015用户已连接!当前在线人数为1
【websocket】 7349用户已连接!当前在线人数为2
【websocket】 推送消息给7349用户,推送内容:你好, 我是2015用户, 很高兴认识你 !
【websocket】 推送消息给2015用户,推送内容:你好, 我是7349用户, 我也很高兴认识你 !
访问:http://localhost:8080/ws可以打开多个开始连接,一个客户端给另一个客户端发消息。可以服务端推送消息给所有连接的客户端POST:http://localhost:8080/push任意内容
5. 需要完整代码的可私信我