最简单的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