Vis*_*cha 5 java stomp websocket sockjs spring-boot
我正在使用 spring boot 2.1.6 RELEASE,尝试使用 Stomp websockets 进行推送通知。我从这里参考: https: //github.com/netgloo/spring-boot-samples/tree/master/spring-boot-web-socket-user-notification
在我当地一切正常。当部署到具有 HTTPS 连接的服务器时,我在日志中看到的只是此内容。
Handshake failed due to invalid Upgrade header: null
Run Code Online (Sandbox Code Playgroud)
并在浏览器上
Websocket.js:6 WebSocket connection to 'wss://dev.myserver.in/ws/055/chbvjkl4/websocket' failed
Run Code Online (Sandbox Code Playgroud)
我浏览了数十篇 stackoverflow 帖子,几乎每个人都在使用代理服务器。我没有使用任何代理服务器。(请告诉我是否应该使用它以及为什么)
代码片段:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我现在允许 websocket 请求的方式
@Override
public void configure(WebSecurity web) throws Exception {
// Tell Spring to ignore securing the handshake endpoint. This allows the
// handshake to take place unauthenticated
web.ignoring().antMatchers("/ws/**");
}
Run Code Online (Sandbox Code Playgroud)
将在特定操作上调用的推送通知服务:
@Service
public class PushNotificationService {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
/**
* Send notification to users subscribed on channel "/user/queue/notify".
* The message will be sent only to the user with the given username.
*
* @param notification The notification message.
* @param username The username for the user to send notification.
*/
public void sendPushNotification(Notifications notification, String username) {
simpMessagingTemplate.convertAndSendToUser(username, "/queue/notify", notification);
return;
}
}
Run Code Online (Sandbox Code Playgroud)
在前端:
function connect() {
// Create and init the SockJS object
var socket = new SockJS('/ws');
var stompClient = Stomp.over(socket);
// Subscribe the '/notify' channel
stompClient.connect({}, function(frame) {
stompClient.subscribe('/user/queue/notify', function(notification) {
notify(JSON.parse(notification.body));
});
});
Run Code Online (Sandbox Code Playgroud)
这是通知
function notify(message) {
let notificationTitle = message.status;
let body = message.createdOn;
let link = message.url;
if(Notification.permission === "granted") {
showPushNotification(notificationTitle,body,link);
}
else {
Notification.requestPermission(permission => {
if(permission === 'granted') {
showPushNotification(notificationTitle,body,link);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3542 次 |
| 最近记录: |