建立WebSocket连接
使用Java的javax.websocket
库建立WebSocket客户端连接。添加Maven依赖:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
创建客户端类并实现Endpoint
和MessageHandler
:
@ClientEndpoint
public class WebSocketClient {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("Connected to server");
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received: " + message);
processMessage(message);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("Disconnected: " + reason.toString());
}
}
连接WebSocket服务器
使用WebSocketContainer
建立连接:
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(
WebSocketClient.class,
URI.create("ws://your-websocket-server.com:port/path")
);
消息处理与数据解析
实现消息处理方法,使用JSON解析库(如Jackson)处理数据:
private void processMessage(String jsonMessage) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(jsonMessage);
String action = rootNode.get("action").asText();
JsonNode data = rootNode.get("data");
switch (action) {
case "query":
handleQueryRequest(data);
break;
// 其他action处理
}
} catch (IOException e) {
e.printStackTrace();
}
}
数据库查询处理
配置数据库连接(以JDBC为例):
private void handleQueryRequest(JsonNode queryParams) {
String queryType = queryParams.get("type").asText();
String responseKey = queryParams.get("responseKey").asText();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
String sql = buildQuery(queryType, queryParams);
ResultSet rs = conn.createStatement().executeQuery(sql);
JsonNode result = convertResultSetToJson(rs);
sendResponse(responseKey, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
构建响应并返回
将查询结果封装为JSON并返回:
private void sendResponse(String responseKey, JsonNode data) {
ObjectNode response = JsonNodeFactory.instance.objectNode();
response.put("responseKey", responseKey);
response.set("data", data);
try {
session.getBasicRemote().sendText(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
异常处理与重连机制
实现自动重连逻辑:
@OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
if (!session.isOpen()) {
reconnect();
}
}
private void reconnect() {
try {
Thread.sleep(5000); // 等待5秒后重连
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, URI.create(serverUri));
} catch (Exception e) {
e.printStackTrace();
}
}
完整示例整合
将所有组件整合为完整解决方案:
public class WebSocketApp {
public static void main(String[] args) {
try {
new WebSocketClient().connect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@ClientEndpoint
public class WebSocketClient {
// 之前的所有方法实现...
public void connect() throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, URI.create("ws://your-server.com/ws"));
}
}
性能优化建议
使用连接池管理数据库连接:
// 使用HikariCP连接池
HikariConfig config = new HikariConfig();
config.setJdbcUrl(DB_URL);
config.setUsername(USER);
config.setPassword(PASS);
HikariDataSource ds = new HikariDataSource(config);
异步处理大量消息:
@OnMessage
public void onMessageAsync(String message) {
CompletableFuture.runAsync(() -> processMessage(message));
}
安全注意事项
实现WebSocket安全验证:
@OnOpen
public void onOpen(Session session, @HeaderParam("Authorization") String auth) {
if (!isValidToken(auth)) {
throw new RuntimeException("Unauthorized");
}
this.session = session;
}
SSL/TLS加密连接:
container.connectToServer(
WebSocketClient.class,
URI.create("wss://secure-server.com/ws") // 注意wss协议
);