标签: spring-websocket

使用Spring websockets定制Stomp Headers

我有一个基本的spring websocket应用程序,它目前向订阅者发送基本数据.目前,系统使用SimpMessageSendingOperations该类作为消息处理程序.如果我调用,SimpMessageSendingOperations.convertAndSend(destination, object)那么订阅的客户端将转换和接收该对象.

我希望能够向客户端发送自定义标头.我尝试过使用这种SimpMessageSendingOperations.convertAndSend(destination, object, headers)方法来做到这一点.但是,自定义标头不包含在stomp消息中.

通过代码调试它看起来像StompHeaderAccessor.toStompHeaderMap()方法调用 toNativeHeaderMap(),它使用本机头和原始本机头映射来构建stomp头.

有没有办法将自定义标头添加到stomp消息?

java spring header stomp spring-websocket

6
推荐指数
1
解决办法
5366
查看次数

使用sockjs stomp over socket无法与Spring 4 WebSocket连接

尝试使用sockjs在套接字上使用Spring 4 WebSocket和STOMP.我遇到了一个问题.

我的配置:

websocket.xml - spring上下文的一部分

<websocket:message-broker application-destination-prefix="/app">  
    <websocket:stomp-endpoint path="/ws">                         
        <websocket:sockjs/>                                       
    </websocket:stomp-endpoint>                                   
    <websocket:simple-broker prefix="/topic"/>                    
</websocket:message-broker>       
Run Code Online (Sandbox Code Playgroud)

控制器代码:

@MessageMapping("/ws")
@SendTo("/topic/ws")
public AjaxResponse hello() throws Exception {
    AjaxResponse ajaxResponse = new AjaxResponse();
    ajaxResponse.setSuccess(true);
    ajaxResponse.addSuccessMessage("WEB SOCKET!!! HELL YEAH!");
    return ajaxResponse;
}
Run Code Online (Sandbox Code Playgroud)

客户端:

var socket = new SockJS("<c:url value='/ws'/>");               
var stompClient = Stomp.over(socket);                             
stompClient.connect({}, function(frame) {                         
    alert('Connected: ' + frame);                                 
    stompClient.send("/app/ws", {}, {});                       
    stompClient.subscribe('/topic/ws', function(response){ 
        alert(response.success);                                  
    });                                                           
});                                                               
Run Code Online (Sandbox Code Playgroud)

输出:

Opening Web Socket... stomp.js:130
GET http://localhost:8080/ws/info 404 (Not Found) sockjs-0.3.js:807
Whoops! Lost connection to undefined …
Run Code Online (Sandbox Code Playgroud)

java stomp spring-mvc sockjs spring-websocket

6
推荐指数
1
解决办法
2万
查看次数

通过SockJS通过STOMP进行安全的WebSocket升级失败,无效升级标头为null

我正在使用一个使用Spring Security和WebSockets的Web应用程序.我可以在没有本地机器问题的情况下使用WebSockets,从嵌入式Tomcat的JAR运行Spring Boot应用程序.但是,当我将相同的JAR /项目上载到CloudFoundry或OpenShift(并将其作为可执行JAR运行)时,建立WebSocket连接时的协议升级失败.

我做了一个小示例项目来演示这个问题(至少当我在我的机器或我的CloudFoundry或OpenShift帐户上尝试它时).它可以在这里找到:https://github.com/shakuzen/spring-stomp-websocket-test

这是一个简单的,简单的例子,但我能够不断重现这个问题.日志中的错误消息是:

2014-10-20T00:46:36.69+0900 [App/0]   OUT 2014-10-19 15:46:36.698 DEBUG 32 --- [io-61088-exec-5] o.s.w.s.s.s.DefaultHandshakeHandler      : Invalid Upgrade header null
Run Code Online (Sandbox Code Playgroud)

默认情况下,DefaultBandshakeHandler的DEBUG日志显示缺少Upgrade标头.但是,如果您查看使用Chrome的开发人员工具(或任何浏览器的等效工具)发送的请求,您会看到请求不同.发送了以下两个请求.

1

GET /hello/info HTTP/1.1
Host: sswss-test.cfapps.io
Connection: keep-alive
Authorization: Basic dGVzdHVzZXI6dGVzdHBhc3M=
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36
Accept: */*
Referer: http://sswss-test.cfapps.io/message
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,ja;q=0.6
Cookie: __VCAP_ID__=693dd6ff1b494f88a2c8567590da500dc44b4818746a45b28dd98a29b2607395; JSESSIONID=C5485065FE0A1DBCDF1F148A63D08FC2
DNT: 1
Run Code Online (Sandbox Code Playgroud)

2

GET ws://sswss-test.cfapps.io/hello/863/olm1kojs/websocket HTTP/1.1
Host: sswss-test.cfapps.io
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Authorization: Basic dGVzdHVzZXI6dGVzdHBhc3M=
Upgrade: websocket
Origin: http://sswss-test.cfapps.io …
Run Code Online (Sandbox Code Playgroud)

stomp spring-security sockjs spring-boot spring-websocket

6
推荐指数
1
解决办法
4589
查看次数

Spring Websockets Max并发连接

tomcat实例可以支持的最大并发websocket连接数是多少?我们希望在任何给定时间提供20000个连接.支持加载的tomcat实例的建议数量是多少?

websocket tomcat7 spring-websocket

6
推荐指数
1
解决办法
3287
查看次数

是否可以通过Spring WebSocket发送同步消息?

我有一个Spring应用程序,它通过Spring WebSocket异步发送消息给另一台服务器.但是对于特定情况我需要同步发送消息,我应该继续使用来自服务器的传入响应的过程.

我不想仅为此进程进行HTTP调用,因为已经有一个开放的TCP连接,我想使用它.

例如,在Tyrus WebSocket实现中,可以通过同步或异步发送消息

session.getBasicRemote().sendText(message);
session.getAsyncRemote().sendText(message);
Run Code Online (Sandbox Code Playgroud)

相关的Tyrus文档链接.

顺便说一下,我没有sub-protocol像Spring WebSocket那样使用STOMP.

java spring websocket tyrus spring-websocket

6
推荐指数
1
解决办法
933
查看次数

春季:向websocket客户端发送消息

我正在使用Spring Boot,RabbitMQ和WebSocket作为POC构建网络聊天,但我有最后一个要点:WebSockets
我希望我的ws客户端连接到特定的端点,例如/room/{id}当有新消息到达时,我希望服务器将响应发送给客户端,但是我搜索了类似内容但未找到。

目前,当消息到达时,我使用RabbitMQ对其进行处理,例如

container.setMessageListener(new MessageListenerAdapter(){
            @Override
            public void onMessage(org.springframework.amqp.core.Message message, Channel channel) throws Exception {
                log.info(message);
                log.info("Got: "+ new String(message.getBody()));
            }
        });
Run Code Online (Sandbox Code Playgroud)

我想要的是,而不是登录它,我想将其发送给客户端,例如: websocketManager.sendMessage(new String(message.getBody()))

java spring rabbitmq spring-boot spring-websocket

6
推荐指数
1
解决办法
1万
查看次数

在Spring Websockets上构建自定义API

我必须在Websockets上实现自定义API,这需要:

  • 自定义WAMP类子协议
  • 套接字URI中的路径参数

所以我有以下问题:

  • 是否有任何关于在Spring中实现自定义子协议的文档或指南?协议要求必须在Sec-Websocket-Protocol字段中指定确切的版本.哪个字段可以在服务器端读取?
  • 将路径参数传递给消息处理程序的正确方法是什么?我可以在处理程序注册中使用ant模式

        @Override 
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(customHandler(), "/api/custom/{clientId}");
        }
    
    Run Code Online (Sandbox Code Playgroud)

    但是TextWebSocketHandler似乎没有.我现在通过以下方式扩展默认的HttpSessionHandshakeInterceptor来解决这个问题:

    public class CustomHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
        private static final UriTemplate URI_TEMPLATE = new UriTemplate("/api/custom/{clientId}");
    
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                       WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
            Map<String, String> segments = URI_TEMPLATE.match(request.getURI().getPath());
            attributes.put("CLIENTID", segments.get("clientId"));
    
            return super.beforeHandshake(request, response, wsHandler, attributes);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后在TextWebSocketHandler中访问它:

    public class CustomHandler extends TextWebSocketHandler {
    
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            super.handleTextMessage(session, message);
    
            String clientId …
    Run Code Online (Sandbox Code Playgroud)

spring spring-websocket

6
推荐指数
1
解决办法
688
查看次数

Java SockJS Spring客户端和消息大小

使用SockJS Java客户端,我正在尝试连接到Spring sockjs服务器,并且收到错误消息209(无标题)(错误消息为1009)。Javascript库工作正常。

Transport closed with CloseStatus[code=1009, reason=The decoded text message was too big 
for the output buffer and the endpoint does not support partial messages] in WebSocketClientSockJsSession
[id='9fa30eb453e14a8c8612e1064640646a, url=ws://127.0.0.1:8083/user]
Run Code Online (Sandbox Code Playgroud)

我在服务器上有几个配置类(目前我不知道是否配置这些东西的次数超过了必要):

@Configuration
@EnableWebSocket
public class WebSocketTransportConfig implements WebSocketConfigurer {
    // Important web socket setup. If big message is coming through, it may overflow the buffer and this will lead in disconnect.
    // All messages that are coming through normally (including snapshots) must be order of magnitude smaller, or connection will …
Run Code Online (Sandbox Code Playgroud)

spring websocket sockjs spring-websocket

6
推荐指数
1
解决办法
2769
查看次数

Spring websockets没有STOMP和SockJs,但具有消息代理和路由支持

有没有办法使用Spring提供的工具来连接webSocket而不使用SockJS和STOMP?我需要实现专有的webSocket协议,所以我现在不能使用任何一个.

我已经从以下答案中实施/破解了解决方案,但它需要重新实现我认为我不应该担心的事情.

我想我的问题归结为:有没有办法让我使用2.(下面)的优点,特别是MessageBroker,而不使用STOMP?

一点背景:

我需要做以下事情:

  • 能够在websocket处理程序的每个实例中为我的持久性提供程序注入引用
  • 在我的处理程序对象的单独实例中处理每个webSocket会话
  • 将我在一个端点上收到的消息重新传输到另一个端点上的多个客户端.
  • 通过标准的Text WebSocket连接实现我自己的协议.

到目前为止我尝试过的是:

  1. 使用javax.websocket,我可以在一个单独的实例上处理每个请求.但是,我需要遍历打开的会话并重新传输连接到正确端点的会话.另外,我不能使用Spring注入我的持久性提供程序.这是我到目前为止使用的东西,看起来太hacky.

即(伪代码)

@ServerEndpoint("/trade/{id}")
public String handleMessage(@PathParam(id) String id, webSocketSession session){
 if(id.equalsIgnoreCase("foo"){
      for(Session s: session.getOpenSessions(){
      //do things}
  } else if(id.equalsIgnoreCase("bar")){
      //do other things
  }
 }
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用@MessageMapping("/trade")和使用Spring websocket实现@SendTo("/queue/position-updates").这要求我至少使用STOMP.这意味着要破坏流程中的其他应用程序,这是我目前无法做到的.此外,还有我需要实施的专有协议的问题.

即(伪代码)

@MessageMapping("/trade/{id}")
@SendTo("/trades/all")
public Greeting greeting(String message){
    //do things, return message
}
Run Code Online (Sandbox Code Playgroud)
  1. 目前,我通过实现WebSocketConfigurer类并注册端点来使用Spring websocket实现.这允许我将每个会话放在一个单独的处理程序类中并注入持久性提供程序.但是,我似乎无法获得有关Spring工作的一些好处:
    • 我不能得到的参数{id}registry.addHandler(WebsocketHandlerPool(), "/trade/{id}")WebsocketHandlerPool(),所以我有,当我创建每一个人来解析路径WebsocketHandler.理想情况下,我不想这样做.
    • 如果我不想迭代websocket消息处理程序代码中的所有会话,我必须实现自己的消息代理.对于@MessageMapping和,我没有支持(据我所知)@SendTo.

即(处理程序的伪代码:)

@Override
public void afterConnectionEstablished(WebSocketSession …
Run Code Online (Sandbox Code Playgroud)

java spring spring-websocket java-websocket

6
推荐指数
0
解决办法
1162
查看次数

弹簧stolds websockets与vue.js

我正在尝试使用带有Vue的Spring websockets(STOMP),但无法弄清楚如何做到这一点,或者它是否可能.我的websockets使用普通的JS,但当我尝试使用Vue时,我会卡住.这是我的vue代码:

var app = new Vue({
el: '#app',
data: {
    stompClient: null,
    gold: 0
},
methods: {
    sendEvent: function () {
        this.stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
    }
},
created: function () {
    this.stompClient = Stomp.over(new SockJS('/gs-guide-websocket'));
    this.stompClient.connect()
    this.stompClient.subscribe('/topic/greetings', function (greeting) {
        console.log(JSON.parse(greeting.body).content);
    });
},
Run Code Online (Sandbox Code Playgroud)

})

我的连接和发送功能正在工作,我可以看到后端的消息,但问题是订阅功能.它需要一个回调函数,但这永远不会触发.我也尝试在vue中创建一个方法并调用它

this.stompClient.subscribe('/topic/greetings', vueFunc())
Run Code Online (Sandbox Code Playgroud)

但这也不起作用.我在https://github.com/FlySkyBear/vue-stomp找到了一些库,但我无法弄清楚如何使用它,它看起来非常混乱.我宁愿使用普通的JS.

有人有解决方案吗?谢谢

javascript spring stomp spring-websocket vuejs2

6
推荐指数
1
解决办法
5820
查看次数