Improve encoder/decoder "replace" in Web Socket Client handshake.

This commit is contained in:
vibul 2011-12-11 21:55:36 +11:00
parent dc1655890e
commit 5be24a0943
8 changed files with 42 additions and 42 deletions

View File

@ -47,6 +47,6 @@ public class WebSocketServer {
// Bind and start to accept incoming connections. // Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(9000)); bootstrap.bind(new InetSocketAddress(9000));
System.out.println("Web Socket Server started on 9000. Open your browser and navigate to http://localhost:9000/"); System.out.println("Web Socket Server started on localhost:9000.");
} }
} }

View File

@ -55,8 +55,9 @@ public class App {
MyCallbackHandler callbackHandler = new MyCallbackHandler(); MyCallbackHandler callbackHandler = new MyCallbackHandler();
WebSocketClientFactory factory = new WebSocketClientFactory(); WebSocketClientFactory factory = new WebSocketClientFactory();
// Connect with spec version 17 (try changing it to V10 or V00 and it will // Connect with spec version 17. You can change it to V10 or V00.
// still work ... fingers crossed ;-) // 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"), WebSocketClient client = factory.newClient(new URI("ws://localhost:8080/websocket"),
WebSocketSpecificationVersion.V17, callbackHandler); WebSocketSpecificationVersion.V17, callbackHandler);
@ -72,7 +73,7 @@ public class App {
} }
Thread.sleep(1000); Thread.sleep(1000);
// Ping // Ping - only supported for V10 and up.
System.out.println("WebSocket Client sending ping"); System.out.println("WebSocket Client sending ping");
client.send(new PingWebSocketFrame(ChannelBuffers.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 }))); client.send(new PingWebSocketFrame(ChannelBuffers.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
Thread.sleep(1000); Thread.sleep(1000);

View File

@ -28,6 +28,7 @@ import io.netty.channel.ChannelPipelineFactory;
import io.netty.channel.Channels; import io.netty.channel.Channels;
import io.netty.channel.socket.nio.NioClientSocketChannelFactory; import io.netty.channel.socket.nio.NioClientSocketChannelFactory;
import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketSpecificationVersion; import io.netty.handler.codec.http.websocketx.WebSocketSpecificationVersion;
import java.net.URI; import java.net.URI;
@ -45,7 +46,7 @@ public class WebSocketClientFactory {
Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
/** /**
* Create a new WebSocket client * Create a new WebSocket client.
* *
* @param url * @param url
* URL to connect to. * URL to connect to.
@ -72,7 +73,11 @@ public class WebSocketClientFactory {
@Override @Override
public ChannelPipeline getPipeline() throws Exception { public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline(); ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new WebSocketHttpResponseDecoder());
// If you wish to support HyBi V00, you need to use WebSocketHttpResponseDecoder instead for
// HttpResponseDecoder.
pipeline.addLast("decoder", new HttpResponseDecoder());
pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("ws-handler", clientHandler); pipeline.addLast("ws-handler", clientHandler);
return pipeline; return pipeline;

View File

@ -66,7 +66,7 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channel = e.getChannel(); channel = e.getChannel();
this.handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url, version, null, false); this.handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url, version, null, false);
handshaker.performOpeningHandshake(ctx, channel); handshaker.performOpeningHandshake(channel);
} }
@Override @Override
@ -77,7 +77,7 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme
@Override @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
if (!handshaker.isOpeningHandshakeCompleted()) { if (!handshaker.isOpeningHandshakeCompleted()) {
handshaker.performClosingHandshake(ctx, (HttpResponse) e.getMessage()); handshaker.performClosingHandshake(ctx.getChannel(), (HttpResponse) e.getMessage());
callback.onConnect(this); callback.onConnect(this);
return; return;
} }

View File

@ -22,7 +22,6 @@ import java.security.NoSuchAlgorithmException;
import io.netty.buffer.ChannelBuffer; import io.netty.buffer.ChannelBuffer;
import io.netty.buffer.ChannelBuffers; import io.netty.buffer.ChannelBuffers;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.base64.Base64;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
@ -114,22 +113,20 @@ public abstract class WebSocketClientHandshaker {
/** /**
* Performs the opening handshake * Performs the opening handshake
* *
* @param ctx
* Channel context
* @param channel * @param channel
* Channel * Channel
*/ */
public abstract void performOpeningHandshake(ChannelHandlerContext ctx, Channel channel); public abstract void performOpeningHandshake(Channel channel);
/** /**
* Performs the closing handshake * Performs the closing handshake
* *
* @param ctx * @param channel
* Channel context * Channel
* @param response * @param response
* HTTP response containing the closing handshake details * HTTP response containing the closing handshake details
*/ */
public abstract void performClosingHandshake(ChannelHandlerContext ctx, HttpResponse response) throws WebSocketHandshakeException; public abstract void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException;
/** /**
* Performs an MD5 hash * Performs an MD5 hash

View File

@ -21,13 +21,14 @@ import java.util.Arrays;
import io.netty.buffer.ChannelBuffers; import io.netty.buffer.ChannelBuffers;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values; import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -81,13 +82,11 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
* ^n:ds[4U * ^n:ds[4U
* </pre> * </pre>
* *
* @param ctx
* Channel context
* @param channel * @param channel
* Channel into which we can write our request * Channel into which we can write our request
*/ */
@Override @Override
public void performOpeningHandshake(ChannelHandlerContext ctx, Channel channel) { public void performOpeningHandshake(Channel channel) {
// Make keys // Make keys
int spaces1 = createRandomNumber(1, 12); int spaces1 = createRandomNumber(1, 12);
int spaces2 = createRandomNumber(1, 12); int spaces2 = createRandomNumber(1, 12);
@ -147,7 +146,7 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
channel.write(request); channel.write(request);
ctx.getPipeline().replace("encoder", "ws-encoder", new WebSocket00FrameEncoder()); channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket00FrameEncoder());
} }
/** /**
@ -166,15 +165,15 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
* 8jKS'y:G*Co,Wxa- * 8jKS'y:G*Co,Wxa-
* </pre> * </pre>
* *
* @param ctx * @param channel
* Channel context * Channel
* @param response * @param response
* HTTP response returned from the server for the request sent by * HTTP response returned from the server for the request sent by
* beginOpeningHandshake00(). * beginOpeningHandshake00().
* @throws WebSocketHandshakeException * @throws WebSocketHandshakeException
*/ */
@Override @Override
public void performClosingHandshake(ChannelHandlerContext ctx, HttpResponse response) throws WebSocketHandshakeException { public void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake"); final HttpResponseStatus status = new HttpResponseStatus(101, "WebSocket Protocol Handshake");
if (!response.getStatus().equals(status)) { if (!response.getStatus().equals(status)) {
@ -199,7 +198,7 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
String protocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL); String protocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
this.setSubProtocolResponse(protocol); this.setSubProtocolResponse(protocol);
ctx.getPipeline().replace("decoder", "ws-decoder", new WebSocket00FrameDecoder()); channel.getPipeline().replace(HttpResponseDecoder.class, "ws-decoder", new WebSocket00FrameDecoder());
this.setOpenningHandshakeCompleted(true); this.setOpenningHandshakeCompleted(true);
} }

View File

@ -18,13 +18,14 @@ package io.netty.handler.codec.http.websocketx;
import java.net.URI; import java.net.URI;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values; import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import io.netty.logging.InternalLogger; import io.netty.logging.InternalLogger;
@ -90,13 +91,11 @@ public class WebSocketClientHandshaker10 extends WebSocketClientHandshaker {
* Sec-WebSocket-Version: 8 * Sec-WebSocket-Version: 8
* </pre> * </pre>
* *
* @param ctx
* Channel context
* @param channel * @param channel
* Channel into which we can write our request * Channel into which we can write our request
*/ */
@Override @Override
public void performOpeningHandshake(ChannelHandlerContext ctx, Channel channel) { public void performOpeningHandshake(Channel channel) {
// Get path // Get path
URI wsURL = this.getWebSocketURL(); URI wsURL = this.getWebSocketURL();
String path = wsURL.getPath(); String path = wsURL.getPath();
@ -130,7 +129,7 @@ public class WebSocketClientHandshaker10 extends WebSocketClientHandshaker {
channel.write(request); channel.write(request);
ctx.getPipeline().replace("encoder", "ws-encoder", new WebSocket08FrameEncoder(true)); channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket08FrameEncoder(true));
} }
/** /**
@ -146,15 +145,15 @@ public class WebSocketClientHandshaker10 extends WebSocketClientHandshaker {
* Sec-WebSocket-Protocol: chat * Sec-WebSocket-Protocol: chat
* </pre> * </pre>
* *
* @param ctx * @param channel
* Channel context * Channel
* @param response * @param response
* HTTP response returned from the server for the request sent by * HTTP response returned from the server for the request sent by
* beginOpeningHandshake00(). * beginOpeningHandshake00().
* @throws WebSocketHandshakeException * @throws WebSocketHandshakeException
*/ */
@Override @Override
public void performClosingHandshake(ChannelHandlerContext ctx, HttpResponse response) throws WebSocketHandshakeException { public void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101, "Switching Protocols"); final HttpResponseStatus status = new HttpResponseStatus(101, "Switching Protocols");
if (!response.getStatus().equals(status)) { if (!response.getStatus().equals(status)) {
@ -176,7 +175,7 @@ public class WebSocketClientHandshaker10 extends WebSocketClientHandshaker {
throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, this.expectedChallengeResponseString)); throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, this.expectedChallengeResponseString));
} }
ctx.getPipeline().replace("decoder", "ws-decoder", new WebSocket08FrameDecoder(false, this.allowExtensions)); channel.getPipeline().replace(HttpResponseDecoder.class, "ws-decoder", new WebSocket08FrameDecoder(false, this.allowExtensions));
this.setOpenningHandshakeCompleted(true); this.setOpenningHandshakeCompleted(true);
} }

View File

@ -18,13 +18,14 @@ package io.netty.handler.codec.http.websocketx;
import java.net.URI; import java.net.URI;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values; import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import io.netty.logging.InternalLogger; import io.netty.logging.InternalLogger;
@ -90,13 +91,11 @@ public class WebSocketClientHandshaker17 extends WebSocketClientHandshaker {
* Sec-WebSocket-Version: 13 * Sec-WebSocket-Version: 13
* </pre> * </pre>
* *
* @param ctx
* Channel context
* @param channel * @param channel
* Channel into which we can write our request * Channel into which we can write our request
*/ */
@Override @Override
public void performOpeningHandshake(ChannelHandlerContext ctx, Channel channel) { public void performOpeningHandshake(Channel channel) {
// Get path // Get path
URI wsURL = this.getWebSocketURL(); URI wsURL = this.getWebSocketURL();
String path = wsURL.getPath(); String path = wsURL.getPath();
@ -130,7 +129,7 @@ public class WebSocketClientHandshaker17 extends WebSocketClientHandshaker {
channel.write(request); channel.write(request);
ctx.getPipeline().replace("encoder", "ws-encoder", new WebSocket13FrameEncoder(true)); channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket13FrameEncoder(true));
} }
/** /**
@ -146,15 +145,15 @@ public class WebSocketClientHandshaker17 extends WebSocketClientHandshaker {
* Sec-WebSocket-Protocol: chat * Sec-WebSocket-Protocol: chat
* </pre> * </pre>
* *
* @param ctx * @param channel
* Channel context * Channel
* @param response * @param response
* HTTP response returned from the server for the request sent by * HTTP response returned from the server for the request sent by
* beginOpeningHandshake00(). * beginOpeningHandshake00().
* @throws WebSocketHandshakeException * @throws WebSocketHandshakeException
*/ */
@Override @Override
public void performClosingHandshake(ChannelHandlerContext ctx, HttpResponse response) throws WebSocketHandshakeException { public void performClosingHandshake(Channel channel, HttpResponse response) throws WebSocketHandshakeException {
final HttpResponseStatus status = new HttpResponseStatus(101, "Switching Protocols"); final HttpResponseStatus status = new HttpResponseStatus(101, "Switching Protocols");
if (!response.getStatus().equals(status)) { if (!response.getStatus().equals(status)) {
@ -176,7 +175,7 @@ public class WebSocketClientHandshaker17 extends WebSocketClientHandshaker {
throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, this.expectedChallengeResponseString)); throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, this.expectedChallengeResponseString));
} }
ctx.getPipeline().replace("decoder", "ws-decoder", new WebSocket13FrameDecoder(false, this.allowExtensions)); channel.getPipeline().replace(HttpResponseDecoder.class, "ws-decoder", new WebSocket13FrameDecoder(false, this.allowExtensions));
this.setOpenningHandshakeCompleted(true); this.setOpenningHandshakeCompleted(true);
} }