Я хочу отображать в чате сообщение «Пользователь покинул» или «Пользователь присоединился». Для этого я отправляю заголовок как «имя пользователя»: имя пользователя при подключении.
Код: Выделить всё
const socketFactory = () => {
return new SockJS('http://localhost:8080/ws');
};
const client = Stomp.over(socketFactory);
client.debug = function(str) {
console.log(str);
};
console.log('Connecting with usernamae:', username);
client.connect(
{
'username':username,
},
() => {
if (mounted) {
console.log('WebSocket Connected');
setIsConnected(true);
setError('');
stompClientRef.current = client;
subscriptionRef.current = client.subscribe('/topic/main', (response) => {
try {
const message = JSON.parse(response.body);
setMessages((prev) => [...prev, message]);
} catch (err) {
console.error('Error parsing message:', err);
}
});
}
},
Код: Выделить всё
public class MyHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {
// Retrieve the 'username' header
String username = (String) request.getHeaders().getFirst("username");
// Log the full headers for debugging
System.out.println("Headers: " + request.getHeaders());
// Add the username to session attributes if it is present
if (username != null) {
attributes.put("username", username);
System.out.println("Username isn't null");
System.out.println("username from interceptor: " + username);
} else {
System.out.println("Username is null");
}
return true; // Allow the handshake to proceed
}
Код: Выделить всё
Headers: [host:"localhost:8080", connection:"Upgrade", pragma:"no-cache", cache-control:"no-cache", user-agent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", upgrade:"websocket", origin:"http://localhost:3000", sec-websocket-version:"13", accept-encoding:"gzip, deflate, br, zstd", accept-language:"en-US,en;q=0.9", cookie:"Pycharm-369fb518=23a11f68-6a45-4169-a4fe-9192e647ba9a; Idea-4b25f8b1=8b8f8caf-69fb-4378-8d09-f2eb6981096e", sec-websocket-key:"QYXmmrTxFlzbzBPi8/PKoA==", sec-websocket-extensions:"permessage-deflate; client_max_window_bits"]
Подробнее здесь: https://stackoverflow.com/questions/793 ... -and-react