前置条件,build.gradle引入依赖:
implementation 'org.java-websocket:Java-WebSocket:1.4.0'
封装websocket类:
java
public class WsHelper {
private static Option option = new Option();
public JWebSocketClient client;
public Boolean ping_status = false;
private ActivityWsCallback callback;
private String TAG = "WS";
public void setCallback(ActivityWsCallback callback) {
this.callback = callback;
}
/**
* 初始化websocket连接
*/
public void initSocketClient() {
URI uri = URI.create(option.WSUri);
Logger.e("开始ws连接");
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
handleMessage(message);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.e(TAG, "websocket连接成功");
msgData sn = new msgData();
sn.setSn(getDeviceSN());
msg obj = new msg();
obj.setCommand("init");
obj.setData(sn);
String str = JSON.toJSONString(obj);
sendMsg(str);
heartBeatRunnable.run();
}
@Override
public void onError(Exception ex) {
super.onError(ex);
Log.e(TAG,"websocket连接错误:" + ex);
ping_status = false;
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
Log.e("ws", "websocket断开连接:·code:" + code + "·reason:" + reason + "·remote:" + remote);
ping_status = false;
}
};
connect();
}
//消息发送
public void sendMsg(String msg) {
if (null != client && client.isOpen()) {
client.send(msg);
} else {
ping_status = false;
}
}
/**
* 连接websocket
*/
private void connect() {
if (client.isOpen()) {
return;
}
client.connect();
}
//心跳检测
private static final long HEART_BEAT_RATE = 5 * 1000;
private Handler mHandler = new Handler();
//心跳检测
private Runnable heartBeatRunnable = new Runnable() {
@Override
public void run() {
mHandler.removeCallbacks(heartBeatRunnable);
if (client != null) {
if (client.isClosed()) {
Log.e(TAG, "关闭状态");
reconnectWs();//心跳机制发现断开开启重连
} else {
//发送消息
msgData sn = new msgData();
sn.setSn(getDeviceSN());
msg obj = new msg();
obj.setData(sn);
if (client.isOpen()) {
obj.setCommand("ping");
sendMsg(JSON.toJSONString(obj));
} else {
Log.e(TAG, "异常");
ping_status = false;
reconnectWs();//心跳机制发现断开开启重连
}
}
} else {
Log.e("", "没有初始化");
//如果client已为空,重新初始化连接
initSocketClient();
}
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);
}
};
//开启重连
private void reconnectWs() {
Log.e("", "正在重连");
initSocketClient();
}
public static String getDeviceSN() {
String serialNumber = android.os.Build.SERIAL;
return serialNumber;
}
public class msg {
private String command;
private msgData data;
public msgData getData() {
return data;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public void setData(msgData data) {
this.data = data;
}
}
public class msgData {
private String sn;
private String data;
public void setData(String data) {
this.sn = data;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
}
/**
* 处理收到的消息
* @param message 收到的消息
*/
private void handleMessage(String message) {
// 调用回调接口的方法,将消息传递给调用方
if (callback != null) {
callback.onMessageReceived(message);
}
}
}
定义回调接口 :
java
public interface ActivityWsCallback {
void onMessageReceived(String message);
}
使用:
java
public class YourActivity implements ActivityWsCallback {
private WsHelper wsHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 初始化 WsHelper
wsHelper = new WsHelper();
wsHelper.initSocketClient();
// 设置回调
wsHelper.setCallback(this);
}
// 实现回调接口的方法,处理收到的消息
@Override
public void onMessageReceived(String message) {
// 在这里处理收到的消息
Log.d(TAG, "Received message: " + message);
}
}