use of okhttp3.WebSocket in project Rocket.Chat.Android by RocketChat.
the class RxWebSocket method connect.
public ConnectableFlowable<RxWebSocketCallback.Base> connect(String url) {
final Request request = new Request.Builder().url(url).build();
return Flowable.create((FlowableOnSubscribe<RxWebSocketCallback.Base>) emitter -> httpClient.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
RxWebSocket.this.webSocket = webSocket;
emitter.onNext(new RxWebSocketCallback.Open(RxWebSocket.this.webSocket, response));
}
@Override
public void onFailure(WebSocket webSocket, Throwable err, Response response) {
try {
emitter.onError(new RxWebSocketCallback.Failure(webSocket, err, response));
} catch (OnErrorNotImplementedException ex) {
RCLog.w(ex, "OnErrorNotImplementedException ignored");
}
}
@Override
public void onMessage(WebSocket webSocket, String text) {
emitter.onNext(new RxWebSocketCallback.Message(webSocket, text));
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
emitter.onNext(new RxWebSocketCallback.Close(webSocket, code, reason));
emitter.onComplete();
}
}), BackpressureStrategy.BUFFER).publish();
}
use of okhttp3.WebSocket in project okhttp by square.
the class RealWebSocket method connect.
public void connect(OkHttpClient client) {
client = client.newBuilder().protocols(ONLY_HTTP1).build();
final int pingIntervalMillis = client.pingIntervalMillis();
final Request request = originalRequest.newBuilder().header("Upgrade", "websocket").header("Connection", "Upgrade").header("Sec-WebSocket-Key", key).header("Sec-WebSocket-Version", "13").build();
call = Internal.instance.newWebSocketCall(client, request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
checkResponse(response);
} catch (ProtocolException e) {
failWebSocket(e, response);
closeQuietly(response);
return;
}
// Promote the HTTP streams into web socket streams.
StreamAllocation streamAllocation = Internal.instance.streamAllocation(call);
// Prevent connection pooling!
streamAllocation.noNewStreams();
Streams streams = streamAllocation.connection().newWebSocketStreams(streamAllocation);
// Process all web socket messages.
try {
listener.onOpen(RealWebSocket.this, response);
String name = "OkHttp WebSocket " + request.url().redact();
initReaderAndWriter(name, pingIntervalMillis, streams);
streamAllocation.connection().socket().setSoTimeout(0);
loopReader();
} catch (Exception e) {
failWebSocket(e, null);
}
}
@Override
public void onFailure(Call call, IOException e) {
failWebSocket(e, null);
}
});
}
use of okhttp3.WebSocket in project okhttp by square.
the class MockWebServer method handleWebSocketUpgrade.
private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink, RecordedRequest request, MockResponse response) throws IOException {
String key = request.getHeader("Sec-WebSocket-Key");
response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key));
writeHttpResponse(socket, sink, response);
// Adapt the request and response into our Request and Response domain model.
String scheme = request.getTlsVersion() != null ? "https" : "http";
// Has host and port.
String authority = request.getHeader("Host");
final Request fancyRequest = new Request.Builder().url(scheme + "://" + authority + "/").headers(request.getHeaders()).build();
final Response fancyResponse = new Response.Builder().code(Integer.parseInt(response.getStatus().split(" ")[1])).message(response.getStatus().split(" ", 3)[2]).headers(response.getHeaders()).request(fancyRequest).protocol(Protocol.HTTP_1_1).build();
final CountDownLatch connectionClose = new CountDownLatch(1);
RealWebSocket.Streams streams = new RealWebSocket.Streams(false, source, sink) {
@Override
public void close() {
connectionClose.countDown();
}
};
RealWebSocket webSocket = new RealWebSocket(fancyRequest, response.getWebSocketListener(), new SecureRandom());
response.getWebSocketListener().onOpen(webSocket, fancyResponse);
String name = "MockWebServer WebSocket " + request.getPath();
webSocket.initReaderAndWriter(name, 0, streams);
try {
webSocket.loopReader();
// Even if messages are no longer being read we need to wait for the connection close signal.
try {
connectionClose.await();
} catch (InterruptedException ignored) {
}
} catch (IOException e) {
webSocket.failWebSocket(e, null);
} finally {
closeQuietly(sink);
closeQuietly(source);
}
}
use of okhttp3.WebSocket in project couchbase-lite-android by couchbase.
the class CBLWebSocket method newRequest.
private Request newRequest() {
Request.Builder builder = new Request.Builder();
// Sets the URL target of this request.
builder.url(uri.toString());
// Set/update the "Host" header:
String host = uri.getHost();
if (uri.getPort() != -1)
host = String.format(Locale.ENGLISH, "%s:%d", host, uri.getPort());
builder.header("Host", host);
// Construct the HTTP request:
if (options != null) {
// Extra Headers
Map<String, Object> extraHeaders = (Map<String, Object>) options.get(kC4ReplicatorOptionExtraHeaders);
if (extraHeaders != null) {
for (Map.Entry<String, Object> entry : extraHeaders.entrySet()) {
builder.header(entry.getKey(), entry.getValue().toString());
}
}
// Cookies:
String cookieString = (String) options.get(kC4ReplicatorOptionCookies);
if (cookieString != null)
builder.addHeader("Cookie", cookieString);
}
// Configure WebSocket related headers:
String protocols = (String) options.get(kC4SocketOptionWSProtocols);
if (protocols != null) {
builder.header("Sec-WebSocket-Protocol", protocols);
}
return builder.build();
}
use of okhttp3.WebSocket in project syndesis by syndesisio.
the class EventsITCase method wsEventsWithToken.
@Test
public void wsEventsWithToken() throws Exception {
OkHttpClient client = new OkHttpClient();
ResponseEntity<EventMessage> r1 = post("/api/v1/event/reservations", null, EventMessage.class);
assertThat(r1.getBody().getEvent().get()).as("event").isEqualTo("uuid");
String uuid = (String) r1.getBody().getData().get();
assertThat(uuid).as("data").isNotNull();
String uriTemplate = EventBusToWebSocket.DEFAULT_PATH + "/" + uuid;
String url = resolveURI(uriTemplate).toString().replaceFirst("^http", "ws");
Request request = new Request.Builder().url(url).addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + tokenRule.validToken()).build();
// lets setup an event handler that we can inspect events on..
WebSocketListener listener = recorder(mock(WebSocketListener.class), WebSocketListener.class);
List<Recordings.Invocation> invocations = recordedInvocations(listener);
CountDownLatch countDownLatch = resetRecorderLatch(listener, 2);
WebSocket ws = client.newWebSocket(request, listener);
// We auto get a message letting us know we connected.
assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onOpen");
assertThat(invocations.get(1).getMethod().getName()).isEqualTo("onMessage");
assertThat(invocations.get(1).getArgs()[1]).isEqualTo(EventMessage.of("message", "connected").toJson());
// ///////////////////////////////////////////////////
// Test that we get notified of created entities
// ///////////////////////////////////////////////////
invocations.clear();
countDownLatch = resetRecorderLatch(listener, 1);
Integration integration = new Integration.Builder().id("1002").name("test").build();
post("/api/v1/integrations", integration, Integration.class);
assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue();
assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onMessage");
assertThat(invocations.get(0).getArgs()[1]).isEqualTo(EventMessage.of("change-event", ChangeEvent.of("created", "integration", "1002").toJson()).toJson());
ws.close(1000, "closing");
}
Aggregations