Skip to content

Commit

Permalink
Clean up the examples
Browse files Browse the repository at this point in the history
Motivation:

The examples have not been updated since long time ago, showing various
issues fixed in this commit.

Modifications:

- Overall simplification to reduce LoC
  - Use system properties to get options instead of parsing args.
  - Minimize option validation
  - Just use System.out/err instead of Logger
  - Do not pass config as parameters - just access it directly
  - Move the main logic to main(String[]) instead of creating a new
    instance meaninglessly
    - Update netty-build-21 to make checkstyle not complain
  - Remove 'throws Exception' clause if possible
- Line wrap at 120 (previously at 80)
- Add an option to enable SSL for most examples
- Use ChannelFuture.sync() instead of await()
- Use System.out for the actual result. Use System.err otherwise.
- Delete examples that are not very useful:
  - applet
  - websocket/html5
  - websocketx/sslserver
  - localecho/multithreaded
- Add run-example.sh which simplifies launching an example from command
  line
- Rewrite FileServer example

Result:

Shorter and simpler examples.  A user can focus more on what it actually
does than miscellaneous stuff.  A user can launch an example very
easily.
  • Loading branch information
trustin committed May 23, 2014
1 parent 47f961b commit 3f81945
Show file tree
Hide file tree
Showing 158 changed files with 2,153 additions and 4,463 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@
* Before returning SocksRequest decoder removes itself from pipeline.
*/
public class SocksAuthRequestDecoder extends ReplayingDecoder<SocksAuthRequestDecoder.State> {
private static final String name = "SOCKS_AUTH_REQUEST_DECODER";

public static String getName() {
return name;
}

private SocksSubnegotiationVersion version;
private int fieldLength;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,6 @@
* Before returning SocksResponse decoder removes itself from pipeline.
*/
public class SocksAuthResponseDecoder extends ReplayingDecoder<SocksAuthResponseDecoder.State> {
private static final String name = "SOCKS_AUTH_RESPONSE_DECODER";

public static String getName() {
return name;
}

private SocksSubnegotiationVersion version;
private SocksAuthStatus authStatus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@
* Before returning SocksRequest decoder removes itself from pipeline.
*/
public class SocksCmdRequestDecoder extends ReplayingDecoder<SocksCmdRequestDecoder.State> {
private static final String name = "SOCKS_CMD_REQUEST_DECODER";

public static String getName() {
return name;
}

private SocksProtocolVersion version;
private int fieldLength;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@
* Before returning SocksResponse decoder removes itself from pipeline.
*/
public class SocksCmdResponseDecoder extends ReplayingDecoder<SocksCmdResponseDecoder.State> {
private static final String name = "SOCKS_CMD_RESPONSE_DECODER";

public static String getName() {
return name;
}

private SocksProtocolVersion version;
private int fieldLength;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@
* Before returning SocksRequest decoder removes itself from pipeline.
*/
public class SocksInitRequestDecoder extends ReplayingDecoder<SocksInitRequestDecoder.State> {
private static final String name = "SOCKS_INIT_REQUEST_DECODER";

public static String getName() {
return name;
}

private final List<SocksAuthScheme> authSchemes = new ArrayList<SocksAuthScheme>();
private SocksProtocolVersion version;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,6 @@
* Before returning SocksResponse decoder removes itself from pipeline.
*/
public class SocksInitResponseDecoder extends ReplayingDecoder<SocksInitResponseDecoder.State> {
private static final String name = "SOCKS_INIT_RESPONSE_DECODER";

public static String getName() {
return name;
}

private SocksProtocolVersion version;
private SocksAuthScheme authScheme;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,6 @@
*/
@ChannelHandler.Sharable
public class SocksMessageEncoder extends MessageToByteEncoder<SocksMessage> {
private static final String name = "SOCKS_MESSAGE_ENCODER";

public static String getName() {
return name;
}

@Override
protected void encode(ChannelHandlerContext ctx, SocksMessage msg, ByteBuf out) throws Exception {
msg.encodeAsByteBuf(out);
Expand Down

This file was deleted.

63 changes: 29 additions & 34 deletions example/src/main/java/io/netty/example/discard/DiscardClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,62 +17,57 @@

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

/**
* Keeps sending random data to the specified address.
*/
public class DiscardClient {
public final class DiscardClient {

private final String host;
private final int port;
private final int firstMessageSize;
static final boolean SSL = System.getProperty("ssl") != null;
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8009"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));

public DiscardClient(String host, int port, int firstMessageSize) {
this.host = host;
this.port = port;
this.firstMessageSize = firstMessageSize;
}
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}

public void run() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new DiscardClientHandler(firstMessageSize));
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
}
p.addLast(new DiscardClientHandler());
}
});

// Make the connection attempt.
ChannelFuture f = b.connect(host, port).sync();
ChannelFuture f = b.connect(HOST, PORT).sync();

// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}

public static void main(String[] args) throws Exception {
// Print usage if no argument is specified.
if (args.length < 2 || args.length > 3) {
System.err.println(
"Usage: " + DiscardClient.class.getSimpleName() +
" <host> <port> [<first message size>]");
return;
}

// Parse options.
final String host = args[0];
final int port = Integer.parseInt(args[1]);
final int firstMessageSize;
if (args.length == 3) {
firstMessageSize = Integer.parseInt(args[2]);
} else {
firstMessageSize = 256;
}

new DiscardClient(host, port, firstMessageSize).run();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,59 +21,39 @@
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Handles a client-side channel.
*/
public class DiscardClientHandler extends SimpleChannelInboundHandler<Object> {

private static final Logger logger = Logger.getLogger(
DiscardClientHandler.class.getName());

private final int messageSize;
private ByteBuf content;
private ChannelHandlerContext ctx;

public DiscardClientHandler(int messageSize) {
if (messageSize <= 0) {
throw new IllegalArgumentException(
"messageSize: " + messageSize);
}
this.messageSize = messageSize;
}

@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
public void channelActive(ChannelHandlerContext ctx) {
this.ctx = ctx;

// Initialize the message.
content = ctx.alloc().directBuffer(messageSize).writeZero(messageSize);
content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);

// Send the initial messages.
generateTraffic();
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
public void channelInactive(ChannelHandlerContext ctx) {
content.release();
}

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
public void messageReceived(ChannelHandlerContext ctx, Object msg) {
// Server is supposed to send nothing, but if it sends something, discard it.
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
logger.log(
Level.WARNING,
"Unexpected exception from downstream.",
cause);
cause.printStackTrace();
ctx.close();
}

Expand All @@ -87,9 +67,12 @@ private void generateTraffic() {

private final ChannelFutureListener trafficGenerator = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
generateTraffic();
} else {
future.cause().printStackTrace();
future.channel().close();
}
}
};
Expand Down
Loading

0 comments on commit 3f81945

Please sign in to comment.