1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| public class WebSocketService { private static OkHttpClient mClient; private WebSocket websocket; private IWebSocketServiceListener webSocketServiceListener;
private int retryTimes = 0;
private static int MAX_RETRY_TIMES = 5;
public WebSocketService(IWebSocketServiceListener webSocketServiceListener){ this.webSocketServiceListener = webSocketServiceListener; connect(); }
public void connect(){ if(mClient == null){ mClient = new OkHttpClient.Builder() .readTimeout(5, TimeUnit.SECONDS) .writeTimeout(5, TimeUnit.SECONDS) .connectTimeout(5, TimeUnit.SECONDS)
.build(); } String url = "wss://..."; Request request = new Request.Builder().get().url(url).build(); websocket = mClient.newWebSocket(request, new MyWebSocketListener()); }
public void reConnect(){ close(); connect(); }
public boolean sendMsg(String msg){ return websocket.send(msg); }
public void close(){ if(websocket != null){ websocket.close(1001, "客户端主动关闭连接"); websocket = null; } }
class MyWebSocketListener extends WebSocketListener { @Override public void onOpen(WebSocket webSocket, Response response) { super.onOpen(webSocket, response); heartBeatTimer = new Timer(); heartBeatTimerTask = new TimerTask() { @Override public void run() { webSocket.send("ping"); } }; heartBeatTimer.schedule(heartBeatTimerTask, 0, 10000); } @Override public void onClosed(WebSocket webSocket, int code, String reason) { super.onClosed(webSocket, code, reason); webSocketServiceListener.onWSClosed(webSocket, code, reason); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { super.onClosing(webSocket, code, reason); webSocketServiceListener.onWSClosing(webSocket, code, reason); if(retryTimes<MAX_RETRY_TIMES){ reConnect(); retryTimes ++; } } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { super.onFailure(webSocket, t, response); webSocketServiceListener.onWSFailure(webSocket, t, response); } @Override public void onMessage(WebSocket webSocket, String text) { super.onMessage(webSocket, text); JSONObject json = JSONObject.parseObject(text); if("ping".equals(json.getString("type"))){ heartBeat(); } webSocketServiceListener.onWSMessage(webSocket, text); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { super.onMessage(webSocket, bytes); webSocketServiceListener.onWSMessage(webSocket, bytes); } } }
|