springboot+websocket-1 最简化 4个回调函数

最简单的ws连接,暂时只用来接收client的数据,并在server打印。

配置文件

@Configuration
public class WebsocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

回调函数

@Component
@ServerEndpoint("/cmd/ws/{shopId}")
@Slf4j
public class CmdWebsocket {

    private Session session;

    @OnOpen
    public void onOpen(@PathParam(value = "shopId") String shopId, Session session) {
        this.session = session;
        log.debug("cmd.ws on OPEN: {}", shopId);
    }

    @OnClose
    public void onClose(@PathParam(value = "shopId") String shopId) {
        log.debug("cmd.ws on CLOSE: {}", shopId);
    }

    @OnError
    public void onError(@PathParam(value = "shopId") String shopId, Throwable error) {
        log.error("cmd.ws on ERROR: shop_id={}\nerr_msg={}\nstack_trace={}", shopId, error.getMessage(), error.getStackTrace());
    }

    @OnMessage
    public void onMessage(@PathParam(value = "shopId") String shopId, String message) {
        log.debug("cmd.ws on MESSAGE: shop_id={}\nmessage={}", shopId, message);
    }
}

测试结果:

15:21:32.003 [http-nio-8080-exec-3] DEBUG c.l.n.m.c.CmdWebsocket - [onOpen,31] - cmd.ws on OPEN: 1000
15:21:37.972 [http-nio-8080-exec-4] DEBUG c.l.n.m.c.CmdWebsocket - [onMessage,47] - cmd.ws on MESSAGE: shop_id=1000
message=我来了
15:21:44.376 [http-nio-8080-exec-5] DEBUG c.l.n.m.c.CmdWebsocket - [onOpen,31] - cmd.ws on OPEN: 1001
15:22:04.381 [http-nio-8080-exec-6] DEBUG c.l.n.m.c.CmdWebsocket - [onMessage,47] - cmd.ws on MESSAGE: shop_id=1001
message={name=的, age=1, gender=1}}
15:22:09.522 [http-nio-8080-exec-7] DEBUG c.l.n.m.c.CmdWebsocket - [onOpen,31] - cmd.ws on OPEN: 1002
15:22:35.093 [http-nio-8080-exec-8] DEBUG c.l.n.m.c.CmdWebsocket - [onMessage,47] - cmd.ws on MESSAGE: shop_id=1002
message=一串json字符串。后续再考虑使用pb。
15:22:38.278 [http-nio-8080-exec-9] DEBUG c.l.n.m.c.CmdWebsocket - [onClose,37] - cmd.ws on CLOSE: 1001
15:22:40.511 [http-nio-8080-exec-10] DEBUG c.l.n.m.c.CmdWebsocket - [onClose,37] - cmd.ws on CLOSE: 1002
15:22:43.163 [http-nio-8080-exec-1] DEBUG c.l.n.m.c.CmdWebsocket - [onClose,37] - cmd.ws on CLOSE: 1000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值