package cn.weblab.plugin.socket;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.project.Project;
import cn.weblab.plugin.util.ConsoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class MyLogWebSocketClient extends WebSocketClient {
Logger log=LoggerFactory.getLogger(MyLogWebSocketClient.class);
private Project project;
private static List<MyLogWebSocketClient> list = new ArrayList<>();
/**
* construct a instance
*
* @param serverUri need to be connected
*/
public MyLogWebSocketClient(String serverUri, Project project) throws URISyntaxException {
super(new URI(serverUri));
this.project = project;
this.setConnectionLostTimeout(0);
if (list.isEmpty()) {
return;
}
for (MyLogWebSocketClient client : list) {
client.close();
}
list.clear();
list.add(this);
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info("在线日志socket连接成功");
ConsoleView logConsole = ConsoleUtil.getLogConsole(project);
logConsole.print("连接建立成功\n", ConsoleViewContentType.ERROR_OUTPUT);
}
@Override
public void onMessage(String s) {
s = s.substring(8);
// if (s.equals("---pong---")) {
// return;
// }
ConsoleView logConsole = ConsoleUtil.getLogConsole(project);
logConsole.print(s, ConsoleViewContentType.NORMAL_OUTPUT);
}
@Override
public void onClose(int i, String s, boolean b) {
log.info("在线日志socket断开");
ConsoleView logConsole = ConsoleUtil.getLogConsole(project);
logConsole.print("在线日志socket断开,请重新连接\n", ConsoleViewContentType.ERROR_OUTPUT);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
// @Override
// public void onWebsocketPong(WebSocket conn, Framedata f) {
// try {
// Thread.sleep(1000 * 10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println("pong");
// this.onWebsocketPing(conn, f);
// super.onWebsocketPong(conn, f);
// }
@Override
public void onWebsocketPing(WebSocket conn, Framedata f) {
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
send("---pong---");
}
@Deprecated
public static void destroy() {
if (list.isEmpty())
return;
for (MyLogWebSocketClient client : list) {
client.close();
}
list.clear();
}
public static void main(String[] args) throws URISyntaxException, InterruptedException {
// MyWebSocketClient client = new MyWebSocketClient("ws://localhost:8080/websocket/A");
// boolean b = client.connectBlocking();
// System.out.println(b);
// client.send("hello");
// client.send("hello");
// client.send("hello");
// client.send("hello");
// client.close();
}
}
java代码实现websocket客户端连接
最新推荐文章于 2024-10-08 14:44:14 发布