webSocket是HTML5的一种新协议,它实现了服务端与客户端的全双工通信,建立在传输层,tcp协议之上,即浏览器与服务端需要先建立tcp协议,再发送webSocket连接建立请求。webSocket的连接:客户端发送请求信息,服务端接受到请求并返回相应的信息。连接建立。客户端发送http请求时,通过 Upgrade:webSocket Connection:Upgrade 告知服务器需要建立的是webSocket连接,并且还会传递webSocket版本号,协议的字版本号,原始地址,主机地址, webSocket相互通信的Header很小,大概只有2Bytes
SpringBoot结合WebSocket实现群发消息
一. 消息群发
1. 导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
2. 新建WebSocket配置类
@Configuration
public class WebsocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
3. 新建WebSocket服务端
@ServerEndpoint("/test")
@Component
@Slf4j
public class MyWebsocketServer {/*** 存放所有在线的客户端*/private static Map<String, Session> clients = new ConcurrentHashMap<>();@OnOpenpublic void onOpen(Session session) {log.info("有新的客户端连接了: {}", session.getId());//将新用户存入在线的组clients.put(session.getId(), session);}/*** 客户端关闭* @param session session*/@OnClosepublic void onClose(Session session) {log.info("有用户断开了, id为:{}", session.getId());//将掉线的用户移除在线的组里clients.remove(session.getId());}/*** 发生错误* @param throwable e*/@OnErrorpublic void onError(Throwable throwable) {throwable.printStackTrace();}/*** 收到客户端发来消息* @param message 消息对象*/@OnMessagepublic void onMessage(String message) {log.info("服务端收到客户端发来的消息: {}", message);this.sendAll(message);}/*** 群发消息* @param message 消息内容*/private void sendAll(String message) {for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {sessionEntry.getValue().getAsyncRemote().sendText(message);}}
}
4. 启动后,客户端连接websocket
5. 客户端发送消息得到的响应和服务端的响应
- 客户端
- 服务端
SpringBoot结合WebSocket实现一对一发送消息
导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId>
</dependency>
新建Websocket配置类
@Configuration
public class WebsocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
新建消息对象
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message {private String userId;private String message;
}
新建websocket服务
@ServerEndpoint("/test-one")
@Component
@Slf4j
public class MyOneToOneServer {/*** 用于存放所有在线客户端*/private static Map<String, Session> clients = new ConcurrentHashMap<>();private Gson gson = new Gson();@OnOpenpublic void onOpen(Session session) {log.info("有新的客户端上线: {}", session.getId());clients.put(session.getId(), session);}@OnClosepublic void onClose(Session session) {String sessionId = session.getId();log.info("有客户端离线: {}", sessionId);clients.remove(sessionId);}@OnErrorpublic void onError(Session session, Throwable throwable) {throwable.printStackTrace();if (clients.get(session.getId()) != null) {clients.remove(session.getId());}}@OnMessagepublic void onMessage(String message) {log.info("收到客户端发来的消息: {}", message);this.sendTo(gson.fromJson(message, Message.class));}/*** 发送消息** @param message 消息对象*/private void sendTo(Message message) {Session s = clients.get(message.getUserId());if (s != null) {try {s.getBasicRemote().sendText(message.getMessage());} catch (IOException e) {e.printStackTrace();}}}
}
测试
- 上线两个客户端
- 使用其中一个客户端发送消息给另外一个,只需要带上另外一个客户端的id
- 接收方客户端