java websocket客户端_java 实现WebSocketClient客户端

时间:2025-03-28 14:24:22

java 实现WebSocketClient客户端案例,向websocket服务端发送消息监听消息,并实现发送马上接受返回值即时调用的方式

代码

public class MyWebSocket extends WebSocketClient {

private int code;

private String message;

private boolean isPagefinished;

public MyWebSocket(URI serverUri) {

super(serverUri);

();

}

public void waitConnect(){

try {

();

} catch (InterruptedException e) {

((),e);

}

}

@Override

public void onOpen(ServerHandshake serverHandshake) {

("###建立连接");

}

@Override

public void onMessage(String s) {

//("接受消息:"+s);

synchronized(this) {

if (!(s)) {

JSONObject obj = (s);

if (("id") && ("id") == code) {

//处理交互消息

= s;

();

if(("id")!=900)("接受内容消息:"+s);

}else if(("method") && "".equals(("method"))){

//处理事件消息

JSONObject eventObj=("params");

//渲染完成事件

if(("name")&&("firstMeaningfulPaint".equals(("name"))||"networkIdle".equals(("name")))){

(true);

}

("接受事件消息:"+s);

}

}

}

}

@Override

public void onClose(int i, String s, boolean b) {

("###关闭连接:"+()+"-"+i+"-"+s+"-"+b);

}

@Override

public void onError(Exception e) {

("###通信错误"+(),e);

}

public String sendAndGet(String text,int code) {

synchronized(this) {

message = null;

= code;

try {

(text);

(120000);

} catch (InterruptedException e) {

((), e);

}

}

return message;

}

public int getCode() {

return code;

}

public void setCode(int code) {

= code;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

= message;

}

public boolean isPagefinished() {

return isPagefinished;

}

public void setPagefinished(boolean pagefinished) {

isPagefinished = pagefinished;

}

}

依赖

-websocket

Java-WebSocket

1.4.0