我的解决方案是不使用SockJS协议,而是使用Python中的"普通老式WebSocket",并使用websockets包,在其中发送Stomp消息,使用stomper包。stomper包只生成字符串作为"消息",你只需使用ws.send(message)
将这些消息通过WebSocket发送。
服务器上的Spring WebSockets配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/my-ws-app");
}
}
在 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]
self.message = ''.join(sp[7:])[0:-1]
这并不是最完整的解决方案。没有退订功能,而且Stomp订阅的id是随机生成的,无法“记忆”。但是,stomper库提供了创建取消订阅消息的功能。
任何发送到/something-to-subscribe-to
的服务器端内容都将被所有已订阅它的Python客户端接收。
@Controller
public class SomeController {
@Autowired
private SimpMessagingTemplate template;
@Scheduled(fixedDelayString = "1000")
public void blastToClientsHostReport(){
template.convertAndSend("/something-to-subscribe-to", "hello world");
}
}
}