本文主要是websoket客户端编写,其主要内容(要求)为通过websocket与第三方服务进行交互,并将收到的消息通过http协议转发至另一服务。
WebSocketClient 客户端
package com.eagle.web.config;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;
/**
*
*
* @author 豆腐脑
* @date 2023-2-20
*/
@Slf4j
@Component
@Configuration
public class WebSocketClientConfig {
@Value("${webs.ws}")
private String ws; // 第三方服务器的websocket接口
@Value("${webs.httpUrl}")
private String httpUrl; // http接口
public static WebSocketClient client;
// 是否连接
public static boolean isConnect = false;
// 单例线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
@Bean
public WebSocketClient getWebSocketClient() {
try {
client = new WebSocketClient(new URI(ws), new Draft_6455()) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info("握手成功!");
isConnect = true;
}
@Override
public void onMessage(String msg) {
log.info("收到服务器端的消息:" + msg);
// 判断msg是否为空
if (null != msg && !msg.trim().equals("")) {
// 异步线程加入线程池,进行发送操作
executorService.execute(new WebSocketThread(httpUrl, msg));
}
}
@Override
public void onError(Exception e) {
e.printStackTrace();
executorService.shutdown();
isConnect = false;
log.info("发生错误已关闭");
}
@Override
public void onClose(int i, String s, boolean b) {
log.info("连接已关闭");
executorService.shutdown();
isConnect = false;
}
@Override
public void onMessage(ByteBuffer bytes) {
try {
System.out.println(new String(bytes.array(), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
// 延迟1秒后,第一次执行,然后每隔5秒检测一下是否断线,如果断线进行重连
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (!isConnect) {
WebSocketClient client = getWebSocketClient();
log.info("正在连接中...");
if (client.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)) {
// 未连接状态
try {
client.connect();
} catch (Exception e) {
e.printStackTrace();
}
} else if (client.getReadyState().equals(ReadyState.CLOSING) || client.getReadyState().equals(ReadyState.CLOSED)) {
// 正关闭状态 或者 关闭状态
try {
client.reconnect();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
}
}, 1000, 5000);
// client.connect();// 连接
return client;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
Maven依赖
<!-- websocket作为客户端 -->
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.4.0</version>
</dependency>
HttpClientUtil类
这个工具类是我直接引用的别人的
package com.eagle.web.config;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* HttpClient工具类
*
* @author 豆腐脑
* @date 2023-2-22
*/
public class HttpClientUtil {
/**
* 带参数的get请求
*
* @param url
* @param param
* @return String
*/
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 不带参数的get请求
*
* @param url
* @return String
*/
public static String doGet(String url) {
return doGet(url, null);
}
/**
* 带参数的post请求
*
* @param url
* @param param
* @return String
*/
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 不带参数的post请求
*
* @param url
* @return String
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 传送json类型的post请求
*
* @param url
* @param json
* @return String
*/
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}