我已经使用文档中的spring boot创建了一个基本的websockets示例应用程序。
这是我在春季启动时的socket conf:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends
AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry
stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/message").setAllowedOrigins("*");
}
}
这是我的消息控制器
@Controller
public class MessageController {
private static final Logger logger =
LoggerFactory.getLogger(MessageController.class);
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting sendResponse(Message incomingMessage) {
logger.debug(incomingMessage.getMessage());
return new Greeting("Hello " + incomingMessage.getMessage());
}
}
我使用android中的okhttp使用以下代码连接到套接字:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding mBinding;
private static String TAG;
public static final String SOCKET_ADDR =
"wss://androidspy.herokuapp.com/message";
private OkHttpClient mOkHttpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this,
R.layout.activity_main);
TAG = this.getClass().getSimpleName();
initObjects();
initListeners();
initiateHandshake();
}
private void initObjects() {
mOkHttpClient = new OkHttpClient();
}
private void initListeners() {
//mBinding.btnConnect.setOnClickListener(this::initiateHandshake);
}
private void initiateHandshake() {
Request socketRequest = new Request.Builder()
.url(SOCKET_ADDR)
.build();
WebSocket webSocket = mOkHttpClient.newWebSocket(socketRequest, new
WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hi Server");
Log.d(TAG, String.format("Connected to
%s",webSocket.request().url()));
}
@Override
public void onMessage(WebSocket webSocket, String result) {
Log.d(TAG, String.format("Received %s" ,result));
}
});
mOkHttpClient.dispatcher().executorService().shutdown();
}
使用上面的代码,连接成功没有任何问题。但我在onMessage Callback中没有得到任何响应。
我想知道如何从Android客户端发送消息,以便它调用映射为sendResponse()
的spring服务器中的@MessageMapping("/hello)
方法。
答案 0 :(得分:0)
尝试不关闭连接mOkHttpClient.dispatcher().executorService().shutdown();