Skip to content

API指南

林泽锋 edited this page Jul 20, 2020 · 2 revisions

1、开启websocket的支持的注解

在spring boot的启动类上加上@EnableWebSocketServer注解,并在该注解上设置好需要扫描的路径。

@SpringBootApplication
@EnableWebSocketServer(webSocketScanPackage = {"com.vue.demo.vue"})
public class VueDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(VueDemoApplication.class, args);
    }

}

2、编写后端响应请求组合注解

@WebSocketController
@WebSocketRequestMapping("/user/")
public class UserController {
    
    /**
     * 这个userService就是我们平时在spring里面写的service
     */
    @Autowired
    private UserService userService;

    /**
     * 功能描述: 模拟字段请求的方式来实现根据用户ID来获取用户数据
     *
     * @param userId 用户的流水ID
     * @return
     */
    @WebSocketRequestMapping("getUserVoByUserId")
    public UserVo getUserVoByUserId(String userId) {
        return userService.getUserVoByUserId(userId);
    }

}

3、编写拦截器

只需要实现WebsocketSecurity接口即可实现自定义的权限拦截处理

public class WebsocketSecurityImpl implements WebsocketSecurity {

    /**
    * 这个authService就是我们平时在spring里面写的service
    **/
    @Autowired
    private AuthService authService;

    @Override
    public int level() {
        return 10;
    }

    @Override
    public Boolean authentication(ChannelHandlerContext ctx, SocketRequest socketRequest) {
        Boolean isPass = authService.authUrl(socketRequest.getUrl());
        System.out.println("----我在这里做了一个模拟的鉴权过程---");
        if(!isPass){
            ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtils.objToJson(new SocketResponse(HttpResponseStatus.UNAUTHORIZED.code(), "授权不通过!"))));
        }
        return isPass;
    }
}

4、编写监听器

只需实现WebSocketHandlerListenter接口即可实现监听。

public class WebSocketHandlerListenterImpl implements WebSocketHandlerListenter {

    /**
    * 这个webSocketCloseService就是我们平时在spring里面写的service
    **/
    @Autowired
    private WebSocketCloseService webSocketCloseService;


    @Override
    public int level() {
        return 0;
    }

    /**
     * 功能描述: 当浏览器端的通道关闭的时候的响应处理方法
     *
     * @param ctx 当前的通道对象
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("当前关闭的通道的id是:" + ctx.channel().id().asLongText());
        webSocketCloseService.removeChannel(ctx.channel().id().asLongText());
    }

    @Override
    public void handleShake(ChannelHandlerContext ctx) {
        System.out.println("当前开启的通道的id是:" + ctx.channel().id().asLongText());
    }
}
Clone this wiki locally