소켓끊김 현상 socket disconnect
첫번째 heartbeat 기능을 만들어처리
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic")
.setTaskScheduler(new ConcurrentTaskScheduler()) // 스케줄러 설정
.setHeartbeatValue(new long[] {10000, 10000}); // 10초마다 heartbeat
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}
keep alive 상태를 유지해야하는데, 주로 client사이드에서 관리한다고한다
python 코드 추가
def start_keep_alive(self):
"""Start keep-alive mechanism to send periodic heartbeat/ping frames."""
if self.keep_alive_thread is None:
self.keep_alive_thread = threading.Thread(target=self.keep_alive)
self.keep_alive_thread.daemon = True # Ensure the thread stops with the main program
self.keep_alive_thread.start()
def keep_alive(self):
"""Send a keep-alive frame every `keep_alive_interval` seconds."""
while self.ws and self.ws.keep_running:
try:
# Define a destination for the keep-alive (heartbeat) message
heartbeat_destination = "/app/heartbeat"
# Minimal STOMP frame with a proper destination
heartbeat_frame = (
f"SEND\n"
f"destination:{heartbeat_destination}\n"
f"content-type:application/json\n\n"
f"{{}}\x00" # Sending an empty JSON object as a heartbeat
)
self.ws.send(heartbeat_frame)
print("Sent keep-alive message to /app/heartbeat.")
except Exception as e:
print(f"Keep-alive failed: {e}")
break
time.sleep(self.keep_alive_interval)
def stop_keep_alive(self):
"""Stop the keep-alive mechanism."""
if self.keep_alive_thread:
self.keep_alive_thread = None
print("Stopped keep-alive mechanism.")


