use of com.squareup.okhttp.ws.WebSocketCall in project weex-example by KalicyZhou.
the class WXWebSocketManager method connect.
public void connect(String url) {
try {
mHttpClient = (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance();
} catch (Exception e) {
isSupportWebSocket = false;
return;
}
mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
// Disable timeouts for read
mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);
Request request = new Request.Builder().url(url).build();
WebSocketCall call = WebSocketCall.create(mHttpClient, request);
call.enqueue(this);
}
use of com.squareup.okhttp.ws.WebSocketCall in project incubator-weex by apache.
the class DefaultWebSocketAdapter method connect.
@Override
public void connect(String url, @Nullable final String protocol, EventListener listener) {
this.eventListener = listener;
this.wsEventReporter = WSEventReporter.newInstance();
OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder();
if (protocol != null) {
builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
}
builder.url(url);
wsEventReporter.created(url);
Request wsRequest = builder.build();
WebSocketCall webSocketCall = WebSocketCall.create(okHttpClient, wsRequest);
try {
Field field = WebSocketCall.class.getDeclaredField("request");
field.setAccessible(true);
Request realRequest = (Request) field.get(webSocketCall);
Headers wsHeaders = realRequest.headers();
Map<String, String> headers = new HashMap<>();
for (String name : wsHeaders.names()) {
headers.put(name, wsHeaders.values(name).toString());
}
wsEventReporter.willSendHandshakeRequest(headers, null);
} catch (Exception e) {
e.printStackTrace();
}
webSocketCall.enqueue(new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
ws = webSocket;
eventListener.onOpen();
Headers wsHeaders = response.headers();
Map<String, String> headers = new HashMap<>();
for (String name : wsHeaders.names()) {
headers.put(name, wsHeaders.values(name).toString());
}
wsEventReporter.handshakeResponseReceived(response.code(), Status.getStatusText(String.valueOf(response.code())), headers);
}
@Override
public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
if (type == WebSocket.PayloadType.BINARY) {
wsEventReporter.frameReceived(payload.readByteArray());
} else {
String message = payload.readUtf8();
eventListener.onMessage(message);
wsEventReporter.frameReceived(message);
}
payload.close();
}
@Override
public void onPong(Buffer payload) {
}
@Override
public void onClose(int code, String reason) {
eventListener.onClose(code, reason, true);
wsEventReporter.closed();
}
@Override
public void onFailure(IOException e) {
e.printStackTrace();
if (e instanceof EOFException) {
eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(), WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
wsEventReporter.closed();
} else {
eventListener.onError(e.getMessage());
wsEventReporter.frameError(e.getMessage());
}
}
});
}
use of com.squareup.okhttp.ws.WebSocketCall in project rskj by rsksmart.
the class Web3WebSocketServerTest method smokeTest.
private void smokeTest(byte[] msg) throws Exception {
Web3 web3Mock = mock(Web3.class);
String mockResult = "output";
when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult);
int randomPort = 9998;
TestSystemProperties testSystemProperties = new TestSystemProperties();
List<ModuleDescription> filteredModules = Collections.singletonList(new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList()));
RskWebSocketJsonRpcHandler handler = new RskWebSocketJsonRpcHandler(null);
JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules);
int serverWriteTimeoutSeconds = testSystemProperties.rpcWebSocketServerWriteTimeoutSeconds();
int maxFrameSize = testSystemProperties.rpcWebSocketMaxFrameSize();
int maxAggregatedFrameSize = testSystemProperties.rpcWebSocketMaxAggregatedFrameSize();
assertEquals(DEFAULT_WRITE_TIMEOUT_SECONDS, serverWriteTimeoutSeconds);
assertEquals(DEFAULT_MAX_FRAME_SIZE, maxFrameSize);
assertEquals(DEFAULT_MAX_AGGREGATED_FRAME_SIZE, maxAggregatedFrameSize);
Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort, handler, serverHandler, serverWriteTimeoutSeconds, maxFrameSize, maxAggregatedFrameSize);
websocketServer.start();
OkHttpClient wsClient = new OkHttpClient();
Request wsRequest = new Request.Builder().url("ws://localhost:" + randomPort + "/websocket").build();
WebSocketCall wsCall = WebSocketCall.create(wsClient, wsRequest);
CountDownLatch wsAsyncResultLatch = new CountDownLatch(1);
CountDownLatch wsAsyncCloseLatch = new CountDownLatch(1);
AtomicReference<Exception> failureReference = new AtomicReference<>();
wsCall.enqueue(new WebSocketListener() {
private WebSocket webSocket;
@Override
public void onOpen(WebSocket webSocket, Response response) {
wsExecutor.submit(() -> {
RequestBody body = RequestBody.create(WebSocket.TEXT, msg);
try {
this.webSocket = webSocket;
this.webSocket.sendMessage(body);
this.webSocket.close(1000, null);
} catch (IOException e) {
failureReference.set(e);
}
});
}
@Override
public void onFailure(IOException e, Response response) {
failureReference.set(e);
}
@Override
public void onMessage(ResponseBody message) throws IOException {
JsonNode jsonRpcResponse = OBJECT_MAPPER.readTree(message.bytes());
assertThat(jsonRpcResponse.at("/result").asText(), is(mockResult));
message.close();
wsAsyncResultLatch.countDown();
}
@Override
public void onPong(Buffer payload) {
}
@Override
public void onClose(int code, String reason) {
wsAsyncCloseLatch.countDown();
}
});
if (!wsAsyncResultLatch.await(10, TimeUnit.SECONDS)) {
fail("Result timed out");
}
if (!wsAsyncCloseLatch.await(10, TimeUnit.SECONDS)) {
fail("Close timed out");
}
websocketServer.stop();
Exception failure = failureReference.get();
if (failure != null) {
failure.printStackTrace();
fail(failure.getMessage());
}
}
Aggregations