Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP upgrade handler for Websockets #5569

Merged
merged 8 commits into from
Jan 10, 2023
Prev Previous commit
Next Next commit
Added sample code that shows negotation of extensions. JDK client doe…
…s not support adding the extensions header manually so only server-side code updated.
  • Loading branch information
spericas committed Dec 1, 2022
commit 41808e3a64eb6bf0cd5bb6742cf2b617441c1ac7
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,24 @@ public void onClose(WsSession session, int status, String reason) {

@Override
public Optional<Headers> onHttpUpgrade(HttpPrologue prologue, Headers headers) throws WsUpgradeException {
WritableHeaders<?> upgradeHeaders = WritableHeaders.create();
if (headers.contains(WsUpgradeProvider.PROTOCOL)) {
List<String> subProtocols = headers.get(WsUpgradeProvider.PROTOCOL).allValues(true);
if (subProtocols.contains("chat")) {
Headers upgradeHeaders = WritableHeaders.create().set(WsUpgradeProvider.PROTOCOL, "chat");
return Optional.of(upgradeHeaders); // negotiated
upgradeHeaders.set(WsUpgradeProvider.PROTOCOL, "chat");
} else {
throw new WsUpgradeException("Unable to negotiate WS sub-protocol");
}
}
return Optional.empty();
if (headers.contains(WsUpgradeProvider.EXTENSIONS)) {
List<String> extensions = headers.get(WsUpgradeProvider.EXTENSIONS).allValues(true);
if (extensions.contains("nima")) {
upgradeHeaders.set(WsUpgradeProvider.EXTENSIONS, "nima");
} else {
throw new WsUpgradeException("Unable to negotiate WS extensions");
}
}
return upgradeHeaders.size() > 0 ? Optional.of(upgradeHeaders) : Optional.empty();
}

void resetClosed() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ void testOnce() throws Exception {

java.net.http.WebSocket ws = client.newWebSocketBuilder()
.subprotocols("chat", "mute")
// .header(EXTENSIONS.defaultCase(), "nima") rejected by client
.buildAsync(URI.create("ws://localhost:" + port + "/echo"), listener)
.get(5, TimeUnit.SECONDS);
assertThat(ws.getSubprotocol(), is("chat")); // negotiated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ public class WsUpgradeProvider implements Http1UpgradeProvider {
*/
public static final HeaderName PROTOCOL = Header.create("Sec-WebSocket-Protocol");

/**
* Websocket protocol header name.
*/
public static final HeaderName EXTENSIONS = Header.create("Sec-WebSocket-Extensions");

/**
* Switching response prefix.
*/
Expand Down