Sinais de atividade e mensagens de manutenção Ping/Pong
Detecte cedo conexões WebSocket inativas usando quadros ping/pong e sinais de atividade STOMP, para que o servidor libere recursos e os clientes se reconectem rapidamente.
Sinais de atividade e mensagens de manutenção Ping/Pong é uma aula grátis de WebSockets & Real-Time Systems with Spring no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de WebSockets & Real-Time Systems with Spring, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de WebSockets & Real-Time Systems with Spring inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
The Silent Death Problem
A WebSocket can look open long after the peer has vanished. A laptop lid closes, a network drops, a NAT mapping expires — yet neither side gets a close frame. This is a half-open connection.
Why It Matters
Half-open sockets waste server memory, keep sessions in maps forever, and let the client believe it is still receiving updates. You need an active probe to discover the truth: a heartbeat.
Ping/Pong Control Frames
The WebSocket protocol defines ping and pong control frames. One side sends a ping; a healthy peer must reply with a pong. No pong within a deadline means the connection is dead.
STOMP Heartbeats in Spring
When you use STOMP over WebSocket, Spring exposes heartbeat configuration. The two numbers are the rate (ms) the server sends and the rate it expects to receive heartbeats.
registry.enableSimpleBroker("/topic")
.setHeartbeatValue(new long[]{10000, 10000})
.setTaskScheduler(heartbeatScheduler());A Scheduler Is Required
Heartbeats need a TaskScheduler to fire on time. Without one Spring silently disables them.
@Bean
public ThreadPoolTaskScheduler heartbeatScheduler() {
ThreadPoolTaskScheduler s = new ThreadPoolTaskScheduler();
s.setPoolSize(1);
s.initialize();
return s;
}Client-Side STOMP Heartbeats
The client declares the matching heartbeat interval. Negotiation picks the slower of each side's value.
const client = new StompJs.Client({
brokerURL: 'wss://api.example.com/ws',
heartbeatIncoming: 10000,
heartbeatOutgoing: 10000
});Raw Ping at the Container Level
For plain (non-STOMP) handlers you can send ping frames directly from the server session.
PingMessage ping = new PingMessage(ByteBuffer.wrap(new byte[]{1}));
session.sendMessage(ping);Choosing an Interval
Tune the interval to your needs:
- Too short wastes bandwidth and battery on mobile
- Too long delays detection of dead peers
- 10–30 seconds is a common sweet spot
Beating Idle Timeouts
Proxies and load balancers drop connections that are idle too long (often 60s). A heartbeat doubles as keep-alive traffic that resets those idle timers and stops them from killing a healthy socket.
Reacting to a Missed Beat
When a heartbeat is missed, Spring closes the session and fires afterConnectionClosed. Use that hook to clean up state and let the client trigger its reconnect logic.
@Override
public void afterConnectionClosed(WebSocketSession s, CloseStatus status) {
registry.remove(s.getId());
log.warn("Closed {} - {}", s.getId(), status);
}Heartbeats vs Application Acks
A heartbeat proves the transport is alive; it does not prove your message was processed. For business-level guarantees you still need application acknowledgements on top of heartbeats.
Quick Check
Test your grasp of keep-alives.
Recap
You made connections self-healing:
- Half-open sockets die silently; heartbeats expose them
- Ping/pong control frames probe transport health
- STOMP heartbeats need a
TaskSchedulerand matching client intervals - Heartbeats also defeat proxy idle timeouts
- Use the close callback to clean up and trigger reconnects
Perguntas Frequentes
A aula “Sinais de atividade e mensagens de manutenção Ping/Pong” é grátis?
Sim — o texto completo de “Sinais de atividade e mensagens de manutenção Ping/Pong” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de WebSockets & Real-Time Systems with Spring, atualize para CoddyKit PRO. O curso de WebSockets & Real-Time Systems with Spring inclui 4 aulas no total.
O que vou aprender em “Sinais de atividade e mensagens de manutenção Ping/Pong”?
Detecte cedo conexões WebSocket inativas usando quadros ping/pong e sinais de atividade STOMP, para que o servidor libere recursos e os clientes se reconectem rapidamente. Você pratica WebSockets & Real-Time Systems with Spring com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar WebSockets & Real-Time Systems with Spring?
Nenhuma experiência prévia é necessária. WebSockets & Real-Time Systems with Spring no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Sinais de atividade e mensagens de manutenção Ping/Pong”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de WebSockets & Real-Time Systems with Spring?
Sim. Cada aula de WebSockets & Real-Time Systems with Spring inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Tratamento adequado de erros do WebSocket
- Gestão do ciclo de vida das ligações
- Novas tentativas e alternativas
- Sinais de atividade e mensagens de manutenção Ping/Pong