Add a handler that makes writing websocket clients much easier

This commit is contained in:
Norman Maurer 2013-03-20 10:04:17 +01:00
parent 624bda4695
commit 4bd9c0195f
5 changed files with 220 additions and 11 deletions

View File

@ -0,0 +1,128 @@
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.websocketx;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpHeaders;
import java.net.URI;
/**
* This handler does all the heavy lifting for you to run a websocket client.
*
* It takes care of websocket handshaking as well as processing of Ping, Pong frames. Text and Binary
* data frames are passed to the next handler in the pipeline (implemented by you) for processing.
* Also the close frame is passed to the next handler as you may want inspect it before close the connection if
* the {@code handleCloseFrames} is {@code false}, default is {@code true}.
*
* This implementation will establish the websocket connection once the connection to the remote server was complete.
*/
public class WebSocketClientProtocolHandler extends WebSocketProtocolHandler {
private final WebSocketClientHandshaker handshaker;
private final boolean handleCloseFrames;
/**
* 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
* @param maxFramePayloadLength
* Maximum length of a frame's payload
* @param handleCloseFrames
* {@code true} if close frames should not be forwarded and just close the channel
*/
public WebSocketClientProtocolHandler(URI webSocketURL, WebSocketVersion version, String subprotocol,
boolean allowExtensions, HttpHeaders customHeaders,
int maxFramePayloadLength, boolean handleCloseFrames) {
this(WebSocketClientHandshakerFactory.newHandshaker(webSocketURL, version, subprotocol,
allowExtensions, customHeaders, maxFramePayloadLength), handleCloseFrames);
}
/**
* 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
* @param maxFramePayloadLength
* Maximum length of a frame's payload
*/
public WebSocketClientProtocolHandler(URI webSocketURL, WebSocketVersion version, String subprotocol,
boolean allowExtensions, HttpHeaders customHeaders,
int maxFramePayloadLength) {
this(webSocketURL, version, subprotocol,
allowExtensions, customHeaders, maxFramePayloadLength, true);
}
/**
* Base constructor
*
* @param handshaker
* The {@link WebSocketClientHandshaker} which will be used to issue the handshake once the connection
* was established to the remote peer.
* @param handleCloseFrames
* {@code true} if close frames should not be forwarded and just close the channel
*/
public WebSocketClientProtocolHandler(WebSocketClientHandshaker handshaker, boolean handleCloseFrames) {
this.handshaker = handshaker;
this.handleCloseFrames = handleCloseFrames;
}
/**
* Base constructor
*
* @param handshaker
* The {@link WebSocketClientHandshaker} which will be used to issue the handshake once the connection
* was established to the remote peer.
*/
public WebSocketClientProtocolHandler(WebSocketClientHandshaker handshaker) {
this(handshaker, true);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
if (handleCloseFrames && frame instanceof CloseWebSocketFrame) {
ctx.close();
return;
}
super.messageReceived(ctx, frame);
}
@Override
public void afterAdd(ChannelHandlerContext ctx) {
ChannelPipeline cp = ctx.pipeline();
if (cp.get(WebSocketClientProtocolHandshakeHandler.class) == null) {
// Add the WebSocketClientProtocolHandshakeHandler before this one.
ctx.pipeline().addBefore(ctx.name(), WebSocketClientProtocolHandshakeHandler.class.getName(),
new WebSocketClientProtocolHandshakeHandler(handshaker));
}
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.websocketx;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.handler.codec.http.FullHttpResponse;
class WebSocketClientProtocolHandshakeHandler extends ChannelInboundMessageHandlerAdapter<FullHttpResponse> {
private final WebSocketClientHandshaker handshaker;
public WebSocketClientProtocolHandshakeHandler(WebSocketClientHandshaker handshaker) {
this.handshaker = handshaker;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
handshaker.handshake(ctx.channel()).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(ctx.channel(), msg);
ctx.pipeline().removeAndForward(this);
return;
}
throw new IllegalStateException("WebSocketClientHandshaker should have been non finished yet");
}
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.websocketx;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
abstract class WebSocketProtocolHandler extends ChannelInboundMessageHandlerAdapter<WebSocketFrame> {
@Override
public void messageReceived(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
if (frame instanceof PingWebSocketFrame) {
frame.data().retain();
ctx.channel().write(new PongWebSocketFrame(frame.data()));
return;
}
if (frame instanceof PongWebSocketFrame) {
// Pong frames need to get ignored
return;
}
frame.retain();
ctx.nextInboundMessageBuffer().add(frame);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}

View File

@ -41,7 +41,7 @@ import static io.netty.handler.codec.http.HttpVersion.*;
* HTTP requests (like GET and POST). If you wish to support both HTTP requests and websockets in the one server, refer
* to the <tt>io.netty.example.http.websocketx.server.WebSocketServer</tt> example.
*/
public class WebSocketServerProtocolHandler extends ChannelInboundMessageHandlerAdapter<WebSocketFrame> {
public class WebSocketServerProtocolHandler extends WebSocketProtocolHandler {
private static final AttributeKey<WebSocketServerHandshaker> HANDSHAKER_ATTR_KEY =
new AttributeKey<WebSocketServerHandshaker>(WebSocketServerHandshaker.class.getName());
@ -82,15 +82,7 @@ public class WebSocketServerProtocolHandler extends ChannelInboundMessageHandler
handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
return;
}
if (frame instanceof PingWebSocketFrame) {
frame.data().retain();
ctx.channel().write(new PongWebSocketFrame(frame.data()));
return;
}
frame.retain();
ctx.nextInboundMessageBuffer().add(frame);
super.messageReceived(ctx, frame);
}
@Override

View File

@ -35,7 +35,7 @@ import static io.netty.handler.codec.http.HttpVersion.*;
/**
* Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
*/
public class WebSocketServerProtocolHandshakeHandler
class WebSocketServerProtocolHandshakeHandler
extends ChannelInboundMessageHandlerAdapter<FullHttpRequest> {
private final String websocketPath;