SockJS Python客户端

SockJS Python客户端,python,spring,rabbitmq,stomp,spring-websocket,Python,Spring,Rabbitmq,Stomp,Spring Websocket,我有一个网站(Java+Spring),它依赖WebSocket(对于Spring+RabbitMQ+SockJS)来实现一些功能 我们正在创建一个基于Python的命令行界面,并希望添加一些使用WebSocket已经提供的功能 有人知道如何使用python客户端以便我可以使用SockJS协议进行连接吗 PS_uuu-我知道一个我没有测试过的主题,但它没有订阅主题的能力 PS2_uu2;因为我可以直接连接到并订阅主题,但直接公开RabbitMQ感觉不太对。对第二个选项有何评论?我使用的解决方案是

我有一个网站(Java+Spring),它依赖WebSocket(对于Spring+RabbitMQ+SockJS)来实现一些功能

我们正在创建一个基于Python的命令行界面,并希望添加一些使用WebSocket已经提供的功能

有人知道如何使用python客户端以便我可以使用SockJS协议进行连接吗

PS_uuu-我知道一个我没有测试过的主题,但它没有订阅主题的能力


PS2_uu2;因为我可以直接连接到并订阅主题,但直接公开RabbitMQ感觉不太对。对第二个选项有何评论?

我使用的解决方案是不使用SockJS协议,而是使用“普通的”web套接字,并使用Python中的websockets包,并使用stomper包通过它发送Stomp消息。stomper包只生成“消息”字符串,您只需使用
ws.send(message)

服务器上的Spring WebSocket配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/my-ws-app"); // Note we aren't doing .withSockJS() here
    }

}
在代码的Python客户端:

import stomper
from websocket import create_connection
ws = create_connection("ws://theservername/my-ws-app")
v = str(random.randint(0, 1000))
sub = stomper.subscribe("/something-to-subscribe-to", v, ack='auto')
ws.send(sub)
while not True:
    d = ws.recv()
    m = MSG(d)
现在
d
将是一个Stomp格式的消息,它的格式非常简单。MSG是我编写用来解析它的一个快速而肮脏的类

class MSG(object):
    def __init__(self, msg):
        self.msg = msg
        sp = self.msg.split("\n")
        self.destination = sp[1].split(":")[1]
        self.content = sp[2].split(":")[1]
        self.subs = sp[3].split(":")[1]
        self.id = sp[4].split(":")[1]
        self.len = sp[5].split(":")[1]
        # sp[6] is just a \n
        self.message = ''.join(sp[7:])[0:-1]  # take the last part of the message minus the last character which is \00
这不是最完整的解决方案。没有取消订阅,Stomp订阅的id是随机生成的,不会被“记住”。但是,stomper库为您提供了创建取消订阅消息的功能

服务器端发送给
/要订阅的东西的任何内容都将被订阅它的所有Python客户端接收

@Controller
public class SomeController {

    @Autowired
    private SimpMessagingTemplate template;

    @Scheduled(fixedDelayString = "1000")
    public void blastToClientsHostReport(){
            template.convertAndSend("/something-to-subscribe-to", "hello world");
        }
    }

}

我已经回答了一个特定的问题,即通过WebSocket从Springboot服务器向Python客户端发送STOMP消息,其中包含sockJs回退:。本报告还涉及委员会的上述评论

  • 发送给特定用户
  • 为什么客户端没有收到任何消息
    你最终为此做了什么?@Jeef我们找不到一个好的解决方案,所以我们不得不通过一个附加的API来模拟该功能。@Tk421我们遇到了同样的问题,即将python客户端连接到SockJS+Spring。我们试图在python中使用websocket库。例如ws=websocket.WebSocketApp(“ws://localhost:8080/socket\u name/topic\u name/1/websocket”,。我们能够连接到websocket,但没有收到发送到主题的消息。我们需要在spring中添加任何自定义握手处理程序来实现这一点吗?@RajaVikram我发布了一个工作示例,回答了我如何使用websocket和与spring websocket服务器对话的Python客户端进行踩踏的问题。希望能有所帮助。你觉得如何向特定终结点发送消息?我尝试了以下方法:ws=create_connection(“ws://host:port/prefix”,header=[“Authorization:Token”])pub=stomper.send('/app/connected','嘿,server,我是客户端')ws.send(pub),但是,我的服务器收到错误“消息中没有用户头”