背景
springboot 中使用okhttp3创建webSocket服务端 server1 和客户端
client1,客户端clinet1调用server1用于发送图片,创建客户端client2接收此图片.在Spring
Boot中使用OkHttp3创建WebSocket服务端和客户端,涉及到两个不同的操作:建立WebSocket服务端和创建WebSocket客户端。OkHttp3库主要用于客户端操作,因此对于服务端,我们将使用Spring的WebSocket支持。
步骤 1: 创建WebSocket服务端(Server1)
- 添加Spring WebSocket依赖
在pom.xml
中添加Spring Boot的WebSocket依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocket
创建一个配置类来启用WebSocket并注册一个endpoint:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
- 创建消息处理器
创建一个控制器来处理发送到服务端的消息:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class ImageMessageController {
@MessageMapping("/receive-image")
@SendTo("/topic/image")
public byte[] receiveImage(byte[] imageData) {
// 处理接收到的图片数据
return imageData; // 将图片数据转发到订阅了 /topic/image 的客户端
}
}
步骤 2: 创建WebSocket客户端(Client1)
- 添加OkHttp依赖
在pom.xml
中添加OkHttp3依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version> <!-- 请使用最新版本 -->
</dependency>
- 创建WebSocket客户端
创建一个客户端来连接到WebSocket服务端并发送图片:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public class ImageWebSocketClient extends WebSocketListener {
private final OkHttpClient client = new OkHttpClient();
private WebSocket webSocket;
public void connect(String url) {
Request request = new Request.Builder().url(url).build();
webSocket = client.newWebSocket(request, this);
}
public void sendImage(byte[] imageData) {
if (webSocket != null) {
webSocket.send(ByteString.of(imageData));
}
}
@Override
public void onOpen(WebSocket webSocket, okhttp3.Response response) {
super.onOpen(webSocket, response);
// WebSocket连接成功建立
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
// 处理接收到的二进制消息
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
// 处理WebSocket关闭事件
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, okhttp3.Response response) {
super.onFailure(webSocket, t, response);
// 处理WebSocket连接失败事件
}
public void close() {
if (webSocket != null) {
webSocket.close(1000, "End of session");
}
}
}
步骤 3: 创建另一个客户端(Client2)
创建另一个客户端来接收由Client1发送的图片:
public class ImageReceivingClient extends WebSocketListener {
private final OkHttpClient client = new OkHttpClient();
private WebSocket webSocket;
public void connect(String url) {
Request request = new Request.Builder().url(url).build();
webSocket = client.newWebSocket(request, this);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
// 处理接收到的图片数据
byte[] imageData = bytes.toByteArray();
// 可以在这里将图片数据保存到文件或进行其他处理
}
public void close() {
if (webSocket != null) {
webSocket.close(1000, "End of session");
}
}
}
步骤 4: 使用客户端
在你的服务中,使用上面创建的ImageWebSocketClient
和ImageReceivingClient
来发送和接收图片。
public class WebSocketService {
public void sendImage(String url, byte[] imageData) {
ImageWebSocketClient client = new ImageWebSocketClient();
client.connect(url);
client.sendImage(imageData);
client.close();
}
public void receiveImage(String url) {
ImageReceivingClient client = new ImageReceivingClient();
client.connect(url);
// 保持连接,直到需要断开
}
}
注意事项
- 确保WebSocket服务端和客户端使用相同的协议(ws://或wss://)。
- 在生产环境中,确保使用wss://来加密WebSocket连接。
- 处理WebSocket连接的异常和错误,确保应用的健壮性。