这里是基于Spring整合websoket后来实现的实时通信,这里只有java的代码,通过在线网站 http://www.websocket-test.com/测试即可
1. 导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
2. 拦截器
public class MyHandshakeInterceptor implements HandshakeInterceptor {
/**
* 握手前 可进行业务逻辑处理 例如用户校验啥的
* @param serverHttpRequest
* @param serverHttpResponse
* @param webSocketHandler
* @param map
* @return
* @throws Exception
*/
@Override
public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
return true;
}
/**
* 握手后
* @param serverHttpRequest
* @param serverHttpResponse
* @param webSocketHandler
* @param e
*/
@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
}
}
3. 处理器
可以用set来存储客户端对象,也可以用map来存储,具体根据实际场景来就行,在onOpen()等几个方法中,具体的代码根据自己的业务逻辑来实现即可。
public class MyWebSocketHandler implements WebSocketHandler {
/**
* 用来存储每一个客户端对象对应的WebSocketSession对象
*/
private static final Set<WebSocketSession> users = new CopyOnWriteArraySet<>();
/**
* 链接成功之后的处理
*/
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
users.add(webSocketSession);
System.out.println(webSocketSession.hashCode() + "建立连接成功");
}
/**
* 服务器接收到消息的处理
* @param webSocketSession
* @param webSocketMessage
* @throws Exception
*/
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
try {
webSocketSession.sendMessage(new TextMessage("接收到消息:" + webSocketMessage.getPayload()));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 推送消息给所有人
* @param text
*/
public static void sendMsgToAll(String text) {
for (WebSocketSession session : users) {
try {
session.sendMessage(new TextMessage(text));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 连接异常的处理
* @param webSocketSession
* @param throwable
* @throws Exception
*/
@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
System.out.println(webSocketSession.hashCode() + "连接异常");
throwable.printStackTrace();
}
/**
* 连接关闭时的处理
* @param webSocketSession
* @param closeStatus
* @throws Exception
*/
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
users.remove(webSocketSession);
System.out.println(webSocketSession.hashCode() + "连接关闭");
}
/**
* 是否支持分片消息
* @return
*/
@Override
public boolean supportsPartialMessages() {
return false;
}
}
4. 配置类
这里用一个接口来推送消息给所有连接到服务器的客户端
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
/**
* 配置服务器的ws地址 跨域校验
* @param webSocketHandlerRegistry
*/
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(myWebSocketHandler(), "/webSocketBySpring").addInterceptors(new MyHandshakeInterceptor()).setAllowedOrigins("*");
webSocketHandlerRegistry.addHandler(myWebSocketHandler(), "/sockjs/webSocketBySpring").addInterceptors(new MyHandshakeInterceptor()).setAllowedOrigins("*").withSockJS();
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
}
5. 控制器
@RestController
public class MsgController2 {
@GetMapping("/sendMsg")
public void sendMsg(@RequestParam(value = "text") String text) {
MyWebSocketHandler.sendMsgToAll(text);
}
}
6. 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebSocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebSocketApplication.class,args);
}
}
7. 测试
-
使用不同的浏览器访问http://www.websocket-test.com/
进入到网页后会自动连接到网站系统的websocket服务器,这需要我们先断开连接,将地址填成我们的地址
链接成功调用afterConnectionEstablished()
-
通过定义的接口推送消息
直接通过浏览器调用本地地址http://192.168.16.144:8800/sendMsg?text=你是来拉屎的吗