android与springboot使用websocket进行交互,请将代码写出来
时间: 2023-07-16 15:14:10 浏览: 130
以下是一个 Android 客户端与 Spring Boot 服务器进行 WebSocket 交互的示例代码。
Android 客户端代码:
```java
public class MainActivity extends AppCompatActivity {
private WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectWebSocket();
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://localhost:8080/websocket");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("WebSocket", "Opened");
mWebSocketClient.send("Hello from Android!");
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.messages);
textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("WebSocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("WebSocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
@Override
protected void onDestroy() {
super.onDestroy();
mWebSocketClient.close();
}
}
```
Spring Boot 服务器端代码:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/websocket").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler() {
return new MyWebSocketHandler();
}
}
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
String payload = message.getPayload();
session.sendMessage(new TextMessage("Hello from Spring Boot!"));
}
}
```
这个示例代码中,Android 客户端连接到 `ws://localhost:8080/websocket`,当连接成功后发送一条消息。Spring Boot 服务器端监听 `/websocket` 路径的 WebSocket 连接,并在接收到消息后返回一条消息给客户端。
阅读全文