Support websocket client custom headers. See pull #123

This commit is contained in:
vibul 2011-12-15 15:09:21 +11:00
parent cedbfba07d
commit f5cc1e02fa
9 changed files with 563 additions and 527 deletions

View File

@ -18,6 +18,7 @@ package org.jboss.netty.example.http.websocketx.client;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -55,11 +56,14 @@ public class App {
MyCallbackHandler callbackHandler = new MyCallbackHandler();
WebSocketClientFactory factory = new WebSocketClientFactory();
// Connect with spec version 17. You can change it to V10 or V00.
// If you change it to V00, ping is not supported and remember to change HttpResponseDecoder to
// WebSocketHttpResponseDecoder in the pipeline.
WebSocketClient client = factory.newClient(new URI("ws://localhost:8080/websocket"),
WebSocketVersion.V13, callbackHandler);
HashMap<String, String> customHeaders = new HashMap<String, String>();
customHeaders.put("MyHeader", "MyValue");
// Connect with V13 (RFC 6455). You can change it to V08 or V00.
// If you change it to V00, ping is not supported and remember to change
// HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
WebSocketClient client = factory.newClient(new URI("ws://localhost:8080/websocket"), WebSocketVersion.V13,
callbackHandler, customHeaders);
// Connect
System.out.println("WebSocket Client connecting");

View File

@ -32,13 +32,14 @@ import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.Executors;
/**
* Copied from https://github.com/cgbystrom/netty-tools
*
* A factory for creating WebSocket clients. The entry point for creating and connecting a client. Can and should be
* used to create multiple instances.
* A factory for creating WebSocket clients. The entry point for creating and
* connecting a client. Can and should be used to create multiple instances.
*/
public class WebSocketClientFactory {
@ -54,11 +55,13 @@ public class WebSocketClientFactory {
* Web Socket version to support
* @param callback
* Callback interface to receive events
* @return A WebSocket client. Call {@link WebSocketClient#connect()} to connect.
* @param customHeaders
* Map of custom headers to add to the client request
* @return A WebSocket client. Call {@link WebSocketClient#connect()} to
* connect.
*/
public WebSocketClient newClient(final URI url,
final WebSocketVersion version,
final WebSocketCallback callback) {
public WebSocketClient newClient(final URI url, final WebSocketVersion version, final WebSocketCallback callback,
final Map<String, String> customHeaders) {
ClientBootstrap bootstrap = new ClientBootstrap(socketChannelFactory);
String protocol = url.getScheme();
@ -66,14 +69,16 @@ public class WebSocketClientFactory {
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
}
final WebSocketClientHandler clientHandler = new WebSocketClientHandler(bootstrap, url, version, callback);
final WebSocketClientHandler clientHandler = new WebSocketClientHandler(bootstrap, url, version, callback,
customHeaders);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
// If you wish to support HyBi V00, you need to use WebSocketHttpResponseDecoder instead for
// If you wish to support HyBi V00, you need to use
// WebSocketHttpResponseDecoder instead for
// HttpResponseDecoder.
pipeline.addLast("decoder", new HttpResponseDecoder());

View File

@ -24,6 +24,7 @@ package org.jboss.netty.example.http.websocketx.client;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
@ -43,8 +44,9 @@ import org.jboss.netty.util.CharsetUtil;
/**
* Copied from https://github.com/cgbystrom/netty-tools
*
* Handles socket communication for a connected WebSocket client Not intended for end-users. Please use
* {@link WebSocketClient} or {@link WebSocketCallback} for controlling your client.
* Handles socket communication for a connected WebSocket client Not intended
* for end-users. Please use {@link WebSocketClient} or
* {@link WebSocketCallback} for controlling your client.
*/
public class WebSocketClientHandler extends SimpleChannelUpstreamHandler implements WebSocketClient {
@ -54,18 +56,22 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme
private Channel channel;
private WebSocketClientHandshaker handshaker = null;
private final WebSocketVersion version;
private Map<String, String> customHeaders = null;
public WebSocketClientHandler(ClientBootstrap bootstrap, URI url, WebSocketVersion version, WebSocketCallback callback) {
public WebSocketClientHandler(ClientBootstrap bootstrap, URI url, WebSocketVersion version,
WebSocketCallback callback, Map<String, String> customHeaders) {
this.bootstrap = bootstrap;
this.url = url;
this.version = version;
this.callback = callback;
this.customHeaders = customHeaders;
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channel = e.getChannel();
this.handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url, version, null, false);
this.handshaker = new WebSocketClientHandshakerFactory()
.newHandshaker(url, version, null, false, customHeaders);
handshaker.performOpeningHandshake(channel);
}
@ -118,4 +124,5 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme
public void setUrl(URI url) {
this.url = url;
}
}

View File

@ -18,6 +18,7 @@ package org.jboss.netty.handler.codec.http.websocketx;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
@ -41,16 +42,29 @@ public abstract class WebSocketClientHandshaker {
private String subProtocolResponse = null;
protected Map<String, String> customHeaders = null;
/**
* Base constructor
*
* @param webSocketURL
* URL for web socket communications. e.g
* "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
* @param version
* Version of web socket specification to use to connect to the
* server
* @param subProtocol
* Sub protocol request sent to the server.
* @param customHeaders
* Map of custom headers to add to the client request
*/
public WebSocketClientHandshaker(URI webSocketURL, WebSocketVersion version, String subProtocol) {
public WebSocketClientHandshaker(URI webSocketURL, WebSocketVersion version, String subProtocol,
Map<String, String> customHeaders) {
this.webSocketURL = webSocketURL;
this.version = version;
this.subProtocolRequest = subProtocol;
this.customHeaders = customHeaders;
}
/**
@ -126,7 +140,8 @@ public abstract class WebSocketClientHandshaker {
* @param response
* HTTP response containing the closing handshake details
*/
public abstract void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException;
public abstract void performClosingHandshake(Channel channel, HttpResponse response)
throws WebSocketHandshakeException;
/**
* Performs an MD5 hash

View File

@ -18,6 +18,7 @@ package org.jboss.netty.handler.codec.http.websocketx;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
@ -60,9 +61,12 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
* server
* @param subProtocol
* Sub protocol request sent to the server.
* @param customHeaders
* Map of custom headers to add to the client request
*/
public WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, String subProtocol) {
super(webSocketURL, version, subProtocol);
public WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, String subProtocol,
Map<String, String> customHeaders) {
super(webSocketURL, version, subProtocol, customHeaders);
}
/**
@ -142,6 +146,11 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
if (this.getSubProtocolRequest() != null && !this.getSubProtocolRequest().equals("")) {
request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, this.getSubProtocolRequest());
}
if (customHeaders != null) {
for (String header : customHeaders.keySet()) {
request.addHeader(header, customHeaders.get(header));
}
}
request.setContent(ChannelBuffers.copiedBuffer(key3));
channel.write(request);
@ -182,12 +191,14 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
String upgrade = response.getHeader(Names.UPGRADE);
if (upgrade == null || !upgrade.equals(Values.WEBSOCKET)) {
throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + response.getHeader(Names.UPGRADE));
throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
+ response.getHeader(Names.UPGRADE));
}
String connection = response.getHeader(Names.CONNECTION);
if (connection == null || !connection.equals(Values.UPGRADE)) {
throw new WebSocketHandshakeException("Invalid handshake response connection: " + response.getHeader(Names.CONNECTION));
throw new WebSocketHandshakeException("Invalid handshake response connection: "
+ response.getHeader(Names.CONNECTION));
}
byte[] challenge = response.getContent().array();

View File

@ -16,6 +16,7 @@
package org.jboss.netty.handler.codec.http.websocketx;
import java.net.URI;
import java.util.Map;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
@ -42,8 +43,7 @@ import org.jboss.netty.util.CharsetUtil;
*/
public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
private static final InternalLogger logger = InternalLoggerFactory
.getInstance(WebSocketClientHandshaker08.class);
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker08.class);
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
@ -69,11 +69,12 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web
* socket frame
* @param customHeaders
* Map of custom headers to add to the client request
*/
public WebSocketClientHandshaker08(URI webSocketURL,
WebSocketVersion version, String subProtocol,
boolean allowExtensions) {
super(webSocketURL, version, subProtocol);
public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subProtocol,
boolean allowExtensions, Map<String, String> customHeaders) {
super(webSocketURL, version, subProtocol, customHeaders);
this.allowExtensions = allowExtensions;
}
@ -115,14 +116,12 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
this.expectedChallengeResponseString = base64Encode(sha1);
if (logger.isDebugEnabled()) {
logger.debug(String
.format("WS Version 08 Client Handshake key: %s. Expected response: %s.",
key, this.expectedChallengeResponseString));
logger.debug(String.format("WS Version 08 Client Handshake key: %s. Expected response: %s.", key,
this.expectedChallengeResponseString));
}
// Format request
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.GET, path);
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.addHeader(Names.UPGRADE, Values.WEBSOCKET.toLowerCase());
request.addHeader(Names.CONNECTION, Values.UPGRADE);
request.addHeader(Names.SEC_WEBSOCKET_KEY, key);
@ -132,11 +131,15 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, protocol);
}
request.addHeader(Names.SEC_WEBSOCKET_VERSION, "8");
if (customHeaders != null) {
for (String header : customHeaders.keySet()) {
request.addHeader(header, customHeaders.get(header));
}
}
channel.write(request);
channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder",
new WebSocket08FrameEncoder(true));
channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket08FrameEncoder(true));
}
/**
@ -160,36 +163,28 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
* @throws WebSocketHandshakeException
*/
@Override
public void performClosingHandshake(Channel channel, HttpResponse response)
throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101,
"Switching Protocols");
public void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101, "Switching Protocols");
if (!response.getStatus().equals(status)) {
throw new WebSocketHandshakeException(
"Invalid handshake response status: "
+ response.getStatus());
throw new WebSocketHandshakeException("Invalid handshake response status: " + response.getStatus());
}
String upgrade = response.getHeader(Names.UPGRADE);
if (upgrade == null || !upgrade.equals(Values.WEBSOCKET.toLowerCase())) {
throw new WebSocketHandshakeException(
"Invalid handshake response upgrade: "
throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
+ response.getHeader(Names.UPGRADE));
}
String connection = response.getHeader(Names.CONNECTION);
if (connection == null || !connection.equals(Values.UPGRADE)) {
throw new WebSocketHandshakeException(
"Invalid handshake response connection: "
throw new WebSocketHandshakeException("Invalid handshake response connection: "
+ response.getHeader(Names.CONNECTION));
}
String accept = response.getHeader(Names.SEC_WEBSOCKET_ACCEPT);
if (accept == null
|| !accept.equals(this.expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format(
"Invalid challenge. Actual: %s. Expected: %s", accept,
if (accept == null || !accept.equals(this.expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept,
this.expectedChallengeResponseString));
}

View File

@ -16,6 +16,7 @@
package org.jboss.netty.handler.codec.http.websocketx;
import java.net.URI;
import java.util.Map;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
@ -42,8 +43,7 @@ import org.jboss.netty.util.CharsetUtil;
*/
public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
private static final InternalLogger logger = InternalLoggerFactory
.getInstance(WebSocketClientHandshaker13.class);
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker13.class);
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
@ -69,11 +69,12 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web
* socket frame
* @param customHeaders
* Map of custom headers to add to the client request
*/
public WebSocketClientHandshaker13(URI webSocketURL,
WebSocketVersion version, String subProtocol,
boolean allowExtensions) {
super(webSocketURL, version, subProtocol);
public WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subProtocol,
boolean allowExtensions, Map<String, String> customHeaders) {
super(webSocketURL, version, subProtocol, customHeaders);
this.allowExtensions = allowExtensions;
}
@ -115,14 +116,12 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
this.expectedChallengeResponseString = base64Encode(sha1);
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"WS Version 13 Client Handshake key: %s. Expected response: %s.",
key, this.expectedChallengeResponseString));
logger.debug(String.format("WS Version 13 Client Handshake key: %s. Expected response: %s.", key,
this.expectedChallengeResponseString));
}
// Format request
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.GET, path);
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.addHeader(Names.UPGRADE, Values.WEBSOCKET.toLowerCase());
request.addHeader(Names.CONNECTION, Values.UPGRADE);
request.addHeader(Names.SEC_WEBSOCKET_KEY, key);
@ -132,11 +131,15 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, protocol);
}
request.addHeader(Names.SEC_WEBSOCKET_VERSION, "13");
if (customHeaders != null) {
for (String header : customHeaders.keySet()) {
request.addHeader(header, customHeaders.get(header));
}
}
channel.write(request);
channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder",
new WebSocket13FrameEncoder(true));
channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket13FrameEncoder(true));
}
/**
@ -160,36 +163,28 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
* @throws WebSocketHandshakeException
*/
@Override
public void performClosingHandshake(Channel channel, HttpResponse response)
throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101,
"Switching Protocols");
public void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101, "Switching Protocols");
if (!response.getStatus().equals(status)) {
throw new WebSocketHandshakeException(
"Invalid handshake response status: "
+ response.getStatus());
throw new WebSocketHandshakeException("Invalid handshake response status: " + response.getStatus());
}
String upgrade = response.getHeader(Names.UPGRADE);
if (upgrade == null || !upgrade.equals(Values.WEBSOCKET.toLowerCase())) {
throw new WebSocketHandshakeException(
"Invalid handshake response upgrade: "
throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
+ response.getHeader(Names.UPGRADE));
}
String connection = response.getHeader(Names.CONNECTION);
if (connection == null || !connection.equals(Values.UPGRADE)) {
throw new WebSocketHandshakeException(
"Invalid handshake response connection: "
throw new WebSocketHandshakeException("Invalid handshake response connection: "
+ response.getHeader(Names.CONNECTION));
}
String accept = response.getHeader(Names.SEC_WEBSOCKET_ACCEPT);
if (accept == null
|| !accept.equals(this.expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format(
"Invalid challenge. Actual: %s. Expected: %s", accept,
if (accept == null || !accept.equals(this.expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept,
this.expectedChallengeResponseString));
}

View File

@ -16,6 +16,7 @@
package org.jboss.netty.handler.codec.http.websocketx;
import java.net.URI;
import java.util.Map;
/**
* Instances the appropriate handshake class to use for clients
@ -38,20 +39,23 @@ public class WebSocketClientHandshakerFactory {
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web
* socket frame
* @param customHeaders
* custom HTTP headers
* @throws WebSocketHandshakeException
*/
public WebSocketClientHandshaker newHandshaker(URI webSocketURL, WebSocketVersion version, String subProtocol, boolean allowExtensions) throws WebSocketHandshakeException {
public WebSocketClientHandshaker newHandshaker(URI webSocketURL, WebSocketVersion version, String subProtocol,
boolean allowExtensions, Map<String, String> customHeaders) throws WebSocketHandshakeException {
if (version == WebSocketVersion.V13) {
return new WebSocketClientHandshaker13(webSocketURL, version, subProtocol, allowExtensions);
return new WebSocketClientHandshaker13(webSocketURL, version, subProtocol, allowExtensions, customHeaders);
}
if (version == WebSocketVersion.V08) {
return new WebSocketClientHandshaker08(webSocketURL, version, subProtocol, allowExtensions);
return new WebSocketClientHandshaker08(webSocketURL, version, subProtocol, allowExtensions, customHeaders);
}
if (version == WebSocketVersion.V00) {
return new WebSocketClientHandshaker00(webSocketURL, version, subProtocol);
return new WebSocketClientHandshaker00(webSocketURL, version, subProtocol, customHeaders);
}
throw new WebSocketHandshakeException("Protocol version " + version.toString() + " not supported.");
throw new WebSocketHandshakeException("Protocol " + version.toString() + " not supported.");
}
}