我想创建一个简单的Android应用程序(websocket客户端),该应用程序将连接到websocket服务器。
我已经使用Spring Boot和STOMP创建了websocket服务器,并且可以使用JavaScript客户端成功连接,订阅和向其发送消息,但是我想使用Android应用程序执行相同的操作。
我的Spring Boot Websocket配置为:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends
AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/sowebsocket")
.addInterceptors(new HttpHandshakeInterceptor())
.setAllowedOrigins("*")
.withSockJS();
}
我的JavaScript客户端代码:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.3.0/sockjs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
<script>
var stompClient = null;
function connect() {
var socket = new SockJS('http://localhost:8080/sowebsocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
stompClient.subscribe('/user/queue/user.personal', function (greeting) {
showGreeting(greeting.body.messageText);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
$(function () {
connect();
)};
</script>
答案 0 :(得分:0)
在https://github.com/NaikSoftware/StompProtocolAndroid上找到了相关示例。感谢Nickolay Savchenko(NaikSoftware)