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
| OkHttpClient mClient = new OkHttpClient.Builder() .pingInterval(10, TimeUnit.SECONDS) .build();
String url = "wss://test:9403/";
Request request = new Request.Builder().get().url(url).build();
WebSocket websocket = mClient.newWebSocket(request, new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { super.onOpen(webSocket, response); Log.d("websocket", "onOpen"); boolean isSendSuccess = webSocket.send("{\"type\":2}"); Log.d("websocket", "send: "+isSendSuccess); }
@Override public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text); Log.i("websocket", "onMessage: " + text); try { JSONObject msg = new JSONObject(text); String messageJson = msg.getString("message"); String codeJson = msg.getString("code");
if(messageJson.equals("test")){ JSONObject data = msg.getJSONObject("data"); JSONObject pointsData = data.getJSONObject("pointsData");
JSONArray points = pointsData.getJSONArray("points");
JSONObject point = points.getJSONObject(0); Dot dot = new Dot( point.getInt("counter"), Dot.DotType.valueOf(point.getString("type")) ); EventBus.getDefault().post(new Events.ReceiveDot(dot,true));
} else if(messageJson.equals("pong")){ Log.d(TAG, "pong recv"); } else{ Log.d(TAG, "other msg"); } }catch (JSONException e) { e.printStackTrace(); } }
@Override public void onMessage(WebSocket webSocket, ByteString bytes) { super.onMessage(webSocket, bytes); }
@Override public void onClosed(WebSocket webSocket, int code, String reason) { super.onClosed(webSocket, code, reason); }
@Override public void onFailure(WebSocket webSocket, Throwable throwable, Response response) { super.onFailure(webSocket, throwable, response); Log.e("websocket", "onFailure: " + throwable.getMessage()); } });
|