Java 构建websocket客户端,构建wss客户端,使用wss连接,并发送数据到服务器端,接收服务器端消息文章来源:https://www.toymoban.com/news/detail-539861.html
// 这段代码放到方法里面就可以了
try {
TrustManager trustManager = new X509ExtendedTrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{trustManager}, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
WebSocketClient webSocketClient = new WebSocketClient(new URI(WebsocketUrl)) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
}
@Override
public void onMessage(String s) {
handleMessage(s);//回调函数,在此函数内对数据处理
}
@Override
public void onClose(int i, String s, boolean b) {
}
@Override
public void onError(Exception e) {
}
};
webSocketClient.setSocketFactory(socketFactory);
webSocketClient.connectBlocking();
ReadyState readyState = webSocketClient.getReadyState();
if (!readyState.equals(ReadyState.OPEN)) {
result.setCode(ResultCode.FAIL);
result.setResult(ImmutableMap.of("msg", "websocket连接超时"));
return result;
}
JSONObject object = new JSONObject();
String json = object.toJSONString(ssss);
//发送数据
webSocketClient.send(json);
//对数据做处理
} catch (Exception e) {
e.printStackTrace();
result.setResult(ImmutableMap.of("msg", e));
return result;
}
回调函数处理文章来源地址https://www.toymoban.com/news/detail-539861.html
public static void handleMessage(String s) {
JSONObject jsonObject = JSON.parseObject(s);
if (jsonObject.getJSONArray("data") != null) {
// 你可以在这里存入数据库,如果还需要咋外层进行处理,可以定义一个全局的静态的变量把收到的数据赋值给这个能量
} else {
logger.error("[uwb:handleMessage] :get message err");
}
}
到了这里,关于Java 构建websocket客户端,构建wss客户端,使用wss连接,并发送数据到服务器端,接收服务器端消息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!