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