package com.iplatform.tcp.client.config;
|
|
import com.iplatform.tcp.client.LoginRequest;
|
import com.walker.infrastructure.utils.JsonUtils;
|
import org.java_websocket.client.WebSocketClient;
|
import org.java_websocket.drafts.Draft_6455;
|
import org.java_websocket.handshake.ServerHandshake;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Configuration;
|
|
import java.net.URI;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
@Configuration
|
public class WebSocketClientConfig {
|
|
protected final transient Logger logger = LoggerFactory.getLogger(this.getClass());
|
|
private WebSocketClient webSocketClient = null;
|
|
@Bean
|
public ClientProperties clientProperties(){
|
return new ClientProperties();
|
}
|
|
@Bean
|
public WebSocketClient webSocketClient(ClientProperties properties) {
|
// WebSocketClient webSocketClient = null;
|
try {
|
webSocketClient = new WebSocketClient(new URI(properties.getUrl()),new Draft_6455()) {
|
@Override
|
public void onOpen(ServerHandshake handshake) {
|
logger.info("ws 连接成功");
|
// 连接上就发送登录
|
// LoginRequest request = new LoginRequest();
|
// request.setName(properties.getName());
|
String data = null;
|
// try {
|
// data = JsonUtils.objectToJsonString(request);
|
// } catch (Exception e) {
|
// throw new RuntimeException(e);
|
// }
|
|
Map<String, String> map = new HashMap<>(4);
|
map.put("protocol", "login");
|
map.put("uid", properties.getName());
|
try {
|
data = JsonUtils.objectToJsonString(map);
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
webSocketClient.send(data.getBytes());
|
logger.info("客户端发送登录请求,name = {}", properties.getName());
|
}
|
|
@Override
|
public void onMessage(String message) {
|
logger.info("ws 收到消息"+message);
|
}
|
|
@Override
|
public void onClose(int code, String reason, boolean remote) {
|
logger.info("ws 退出");
|
}
|
|
@Override
|
public void onError(Exception ex) {
|
ex.printStackTrace();
|
logger.info("连接错误"+ex.getMessage());
|
}
|
};
|
webSocketClient.connect();
|
return webSocketClient;
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
}
|