1.添加依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.添加配置
java
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.添加websocket处理器
java
@Setter@Getter
@ServerEndpoint("/{token}")
@Component
public class WebSocketServer {
private Session session;
public static ConcurrentHashMap<String,Session> clients = new ConcurrentHashMap<>();
/**
* 浏览器和服务器在建立连接
* @param session
* @param token
*/
@OnOpen
public void onOpen(Session session, @PathParam( "token") String token){
System.out.println("客户端连接===>"+token);
clients.put(token,session);
}
/**
* 客户端发送消息
* @param message
* @param token
*/
@OnMessage
public void onMessage(String message, @PathParam( "token") String token){
System.out.println("客户端:"+token+",发送消息:"+message);
//发送消息
clients.get(token).getAsyncRemote().sendText(message);
}
/**
* 浏览器和服务器之间断开连接之后会调用此方法.
* @param token
*/
@OnClose
public void onClose(@PathParam( "token") String token){
System.out.println("客户端:"+token+",断开连接");
//删除关系
clients.remove(token);
}
/**
* 通讯异常触发该事件
* @param error
*/
@OnError
public void onError(Throwable error) {
error.printStackTrace();
}
}
4.提供接口获取浏览器发送的消息
java
@RestController
public class MsgContoller {
@RequestMapping("/sendMsg")
public String sendMsg(String token,String msg) throws IOException {
Session session = OrderWebSocketServer.clients.get(token);
session.getBasicRemote().sendText(msg);
return "发送成功";
}
}