1. Maven 坐标引入依赖
# Java-WebSocket 坐标
<!-- /artifact/-websocket/Java-WebSocket -->
<dependency>
<groupId>-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.1</version>
</dependency>
2. WebSocketClient 帮助类,建立长链接实现单例模式,连接断开自动重连机制,代码可以直接使用。
import org.java_websocket.;
import org.java_websocket.;
import org.;
import org.;
import ;
import ;
/**
* websocket client 客户端端控制
*/
public class WebSocketClient extends org.java_websocket. {
private static final Logger logger = ();
// 复制请留意,该位置url需要进行更改
private static String wsUrl = "ws://127.0.0.1:10080//";
private static WebSocketClient instance;
private int sendFlag = 0;
private String result = null;
static {
try {
instance = new WebSocketClient(wsUrl);
();
} catch (URISyntaxException e) {
();
}
}
// 获取到当前实例
public static WebSocketClient getInstance(){
try{
if(instance != null){
if(() == ReadyState.NOT_YET_CONNECTED
|| () == ){
if(()){
();
}
}
}else{
instance = new WebSocketClient(wsUrl);
();
}
}catch (Exception ex){
instance = null;
(" websocket 构建实例出现问题!!" + ex);
}
return instance;
}
// 发送字符串消息
public String sendStr(String text){
synchronized(this){
sendFlag = 1;
(text);
while(sendFlag != 0){
(" 等待返回值中 =============== " + sendFlag);
}
return result;
}
}
private WebSocketClient(String url) throws URISyntaxException {
super(new URI(url));
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
(" ws 服务正常打开!!");
}
@Override
public void onMessage(String s) {
result = s;
sendFlag = 0;
(" ws 接收服务器推送的消息!!" + s);
}
@Override
public void onClose(int i, String s, boolean b) {
result = null;
sendFlag = 0;
(" ws 客户端正常关闭!!");
}
@Override
public void onError(Exception e) {
result = null;
sendFlag = 0;
(" ws 客户端连接出现错误!!");
}
}
3. 在任意位置调用
// 构建实例
private WebSocketClient wsClient = ();
// 发送消息 接收返回值
// result 会同步返回数据,可以直接进行使用。
String result = ("hello ws server!!");
微笑的java
欢迎关注转发评论点赞沟通,让编码不在孤单。