springboot,给我提供一个方法供调用,socket连接springboot服务端,IP是walzzpc,端口号是9090,客户和服务端通讯,服务端主动给客户端发送信息
时间: 2023-10-09 20:05:15 浏览: 76
好的,以下是一个简单的示例代码,供您参考:
1. 在 pom.xml 中添加 Socket 相关依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建一个 WebSocketHandler 处理器类:
```java
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
private WebSocketSession session;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
this.session = session;
System.out.println("连接已建立!");
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println("收到客户端消息:" + message.getPayload());
}
public void sendMessage(String message) throws IOException {
if (session != null && session.isOpen()) {
session.sendMessage(new TextMessage(message));
}
}
}
```
3. 在控制器中注入 WebSocketHandler,并提供一个接口供客户端调用:
```java
@RestController
public class MyController {
@Autowired
private MyWebSocketHandler handler;
@GetMapping("/send")
public void sendMessage(@RequestParam String message) throws IOException {
handler.sendMessage(message);
}
}
```
4. 在应用程序启动类中配置 WebSocket:
```java
@SpringBootApplication
@EnableWebSocket
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}
```
5. 在客户端中连接 WebSocket 服务端并发送消息:
```javascript
const socket = new WebSocket('ws://walzzpc:9090');
socket.onopen = function() {
console.log('连接已建立!');
};
socket.onmessage = function(event) {
console.log('收到服务端消息:' + event.data);
};
socket.send('Hello, Server!');
```
这样,当客户端发送请求到 `http://<your_host>/send?message=<your_message>` 时,服务端就会主动向客户端发送 `<your_message>` 消息。
阅读全文