diff --git a/example/src/main/java/io/netty/example/discard/DiscardClient.java b/example/src/main/java/io/netty/example/discard/DiscardClient.java index 0ff7e8f277..9ed9c8548c 100644 --- a/example/src/main/java/io/netty/example/discard/DiscardClient.java +++ b/example/src/main/java/io/netty/example/discard/DiscardClient.java @@ -30,6 +30,41 @@ import io.netty.channel.socket.nio.NioClientSocketChannelFactory; */ public class DiscardClient { + private final String host; + private final int port; + private final int firstMessageSize; + + public DiscardClient(String host, int port, int firstMessageSize) { + this.host = host; + this.port = port; + this.firstMessageSize = firstMessageSize; + } + + public void run() { + // Configure the client. + ClientBootstrap bootstrap = new ClientBootstrap( + new NioClientSocketChannelFactory( + Executors.newCachedThreadPool(), + Executors.newCachedThreadPool())); + + // Set up the pipeline factory. + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() throws Exception { + return Channels.pipeline( + new DiscardClientHandler(firstMessageSize)); + } + }); + + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + + // Wait until the connection is closed or the connection attempt fails. + future.getChannel().getCloseFuture().awaitUninterruptibly(); + + // Shut down thread pools to exit. + bootstrap.releaseExternalResources(); + } + public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length < 2 || args.length > 3) { @@ -48,43 +83,7 @@ public class DiscardClient { } else { firstMessageSize = 256; } - + new DiscardClient(host, port, firstMessageSize).run(); } - - private final String host; - private final int port; - private final int firstMessageSize; - - public DiscardClient(String host, int port, int firstMessageSize) { - this.host = host; - this.port = port; - this.firstMessageSize = firstMessageSize; - } - - public void run() { - // Configure the client. - ClientBootstrap bootstrap = new ClientBootstrap( - new NioClientSocketChannelFactory( - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool())); - - // Set up the pipeline factory. - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new DiscardClientHandler(firstMessageSize)); - } - }); - - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); - - // Wait until the connection is closed or the connection attempt fails. - future.getChannel().getCloseFuture().awaitUninterruptibly(); - - // Shut down thread pools to exit. - bootstrap.releaseExternalResources(); - } } diff --git a/example/src/main/java/io/netty/example/discard/DiscardServer.java b/example/src/main/java/io/netty/example/discard/DiscardServer.java index 48369e2505..978bc9097c 100644 --- a/example/src/main/java/io/netty/example/discard/DiscardServer.java +++ b/example/src/main/java/io/netty/example/discard/DiscardServer.java @@ -29,8 +29,10 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class DiscardServer { - public static void main(String[] args) throws Exception { - new DiscardServer().run(); + private final int port; + + public DiscardServer(int port) { + this.port = port; } public void run() { @@ -42,13 +44,22 @@ public class DiscardServer { // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new DiscardServerHandler()); } }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new DiscardServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/echo/EchoClient.java b/example/src/main/java/io/netty/example/echo/EchoClient.java index 08d5ed2cc6..3b37e9d1b6 100644 --- a/example/src/main/java/io/netty/example/echo/EchoClient.java +++ b/example/src/main/java/io/netty/example/echo/EchoClient.java @@ -33,6 +33,41 @@ import io.netty.channel.socket.nio.NioClientSocketChannelFactory; */ public class EchoClient { + private final String host; + private final int port; + private final int firstMessageSize; + + public EchoClient(String host, int port, int firstMessageSize) { + this.host = host; + this.port = port; + this.firstMessageSize = firstMessageSize; + } + + public void run() { + // Configure the client. + ClientBootstrap bootstrap = new ClientBootstrap( + new NioClientSocketChannelFactory( + Executors.newCachedThreadPool(), + Executors.newCachedThreadPool())); + + // Set up the pipeline factory. + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() throws Exception { + return Channels.pipeline( + new EchoClientHandler(firstMessageSize)); + } + }); + + // Start the connection attempt. + ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); + + // Wait until the connection is closed or the connection attempt fails. + future.getChannel().getCloseFuture().awaitUninterruptibly(); + + // Shut down thread pools to exit. + bootstrap.releaseExternalResources(); + } + public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length < 2 || args.length > 3) { @@ -51,43 +86,7 @@ public class EchoClient { } else { firstMessageSize = 256; } - + new EchoClient(host, port, firstMessageSize).run(); } - - private final String host; - private final int port; - private final int firstMessageSize; - - public EchoClient(String host, int port, int firstMessageSize) { - this.host = host; - this.port = port; - this.firstMessageSize = firstMessageSize; - } - - public void run() { - // Configure the client. - ClientBootstrap bootstrap = new ClientBootstrap( - new NioClientSocketChannelFactory( - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool())); - - // Set up the pipeline factory. - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new EchoClientHandler(firstMessageSize)); - } - }); - - // Start the connection attempt. - ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); - - // Wait until the connection is closed or the connection attempt fails. - future.getChannel().getCloseFuture().awaitUninterruptibly(); - - // Shut down thread pools to exit. - bootstrap.releaseExternalResources(); - } } diff --git a/example/src/main/java/io/netty/example/echo/EchoServer.java b/example/src/main/java/io/netty/example/echo/EchoServer.java index d16352c1a6..2dda7bc2a9 100644 --- a/example/src/main/java/io/netty/example/echo/EchoServer.java +++ b/example/src/main/java/io/netty/example/echo/EchoServer.java @@ -29,8 +29,10 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class EchoServer { - public static void main(String[] args) throws Exception { - new EchoServer().run(); + private final int port; + + public EchoServer(int port) { + this.port = port; } public void run() { @@ -42,13 +44,22 @@ public class EchoServer { // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new EchoServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/factorial/FactorialClient.java b/example/src/main/java/io/netty/example/factorial/FactorialClient.java index 565e44a79c..b35c5278e9 100644 --- a/example/src/main/java/io/netty/example/factorial/FactorialClient.java +++ b/example/src/main/java/io/netty/example/factorial/FactorialClient.java @@ -29,26 +29,6 @@ import io.netty.channel.socket.nio.NioClientSocketChannelFactory; */ public class FactorialClient { - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 3) { - System.err.println( - "Usage: " + FactorialClient.class.getSimpleName() + - " "); - return; - } - - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - int count = Integer.parseInt(args[2]); - if (count <= 0) { - throw new IllegalArgumentException("count must be a positive integer."); - } - - new FactorialClient(host, port, count).run(); - } - private final String host; private final int port; private final int count; @@ -87,4 +67,24 @@ public class FactorialClient { // Shut down all thread pools to exit. bootstrap.releaseExternalResources(); } + + public static void main(String[] args) throws Exception { + // Print usage if no argument is specified. + if (args.length != 3) { + System.err.println( + "Usage: " + FactorialClient.class.getSimpleName() + + " "); + return; + } + + // Parse options. + String host = args[0]; + int port = Integer.parseInt(args[1]); + int count = Integer.parseInt(args[2]); + if (count <= 0) { + throw new IllegalArgumentException("count must be a positive integer."); + } + + new FactorialClient(host, port, count).run(); + } } diff --git a/example/src/main/java/io/netty/example/factorial/FactorialServer.java b/example/src/main/java/io/netty/example/factorial/FactorialServer.java index c7e0a4ba7d..c8e4290958 100644 --- a/example/src/main/java/io/netty/example/factorial/FactorialServer.java +++ b/example/src/main/java/io/netty/example/factorial/FactorialServer.java @@ -27,8 +27,10 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class FactorialServer { - public static void main(String[] args) throws Exception { - new FactorialServer().run(); + private final int port; + + public FactorialServer(int port) { + this.port = port; } public void run() { @@ -42,6 +44,16 @@ public class FactorialServer { bootstrap.setPipelineFactory(new FactorialServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new FactorialServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/http/file/HttpStaticFileServer.java b/example/src/main/java/io/netty/example/http/file/HttpStaticFileServer.java index d408c36601..9cb73d72cd 100644 --- a/example/src/main/java/io/netty/example/http/file/HttpStaticFileServer.java +++ b/example/src/main/java/io/netty/example/http/file/HttpStaticFileServer.java @@ -22,7 +22,14 @@ import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.socket.nio.NioServerSocketChannelFactory; public class HttpStaticFileServer { - public static void main(String[] args) { + + private final int port; + + public HttpStaticFileServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -33,6 +40,16 @@ public class HttpStaticFileServer { bootstrap.setPipelineFactory(new HttpStaticFileServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new HttpStaticFileServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/http/snoop/HttpClient.java b/example/src/main/java/io/netty/example/http/snoop/HttpClient.java index 1a665e02c5..5cc61acfbb 100644 --- a/example/src/main/java/io/netty/example/http/snoop/HttpClient.java +++ b/example/src/main/java/io/netty/example/http/snoop/HttpClient.java @@ -36,15 +36,13 @@ import io.netty.handler.codec.http.HttpVersion; */ public class HttpClient { - public static void main(String[] args) throws Exception { - if (args.length != 1) { - System.err.println( - "Usage: " + HttpClient.class.getSimpleName() + - " "); - return; - } + private final URI uri; - URI uri = new URI(args[0]); + public HttpClient(URI uri) { + this.uri = uri; + } + + public void run() { String scheme = uri.getScheme() == null? "http" : uri.getScheme(); String host = uri.getHost() == null? "localhost" : uri.getHost(); int port = uri.getPort(); @@ -105,4 +103,16 @@ public class HttpClient { // Shut down executor threads to exit. bootstrap.releaseExternalResources(); } + + public static void main(String[] args) throws Exception { + if (args.length != 1) { + System.err.println( + "Usage: " + HttpClient.class.getSimpleName() + + " "); + return; + } + + URI uri = new URI(args[0]); + new HttpClient(uri).run(); + } } diff --git a/example/src/main/java/io/netty/example/http/snoop/HttpServer.java b/example/src/main/java/io/netty/example/http/snoop/HttpServer.java index e3595b7234..fc0d6d4385 100644 --- a/example/src/main/java/io/netty/example/http/snoop/HttpServer.java +++ b/example/src/main/java/io/netty/example/http/snoop/HttpServer.java @@ -26,7 +26,14 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; * in a pretty plaintext form. */ public class HttpServer { - public static void main(String[] args) { + + private final int port; + + public HttpServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -37,6 +44,16 @@ public class HttpServer { bootstrap.setPipelineFactory(new HttpServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new HttpServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServer.java b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServer.java similarity index 73% rename from example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServer.java rename to example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServer.java index cf7a98cc2b..2f2f5bab4e 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServer.java +++ b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServer.java @@ -28,13 +28,15 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; * A Web Socket echo server for running the autobahn test * suite */ -public class WebSocketServer { - public static void main(String[] args) { - ConsoleHandler ch = new ConsoleHandler(); - ch.setLevel(Level.FINE); - Logger.getLogger("").addHandler(ch); - Logger.getLogger("").setLevel(Level.FINE); +public class AutobahnServer { + private final int port; + + public AutobahnServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); @@ -42,11 +44,21 @@ public class WebSocketServer { // bootstrap.setOption("child.tcpNoDelay", true); // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory()); + bootstrap.setPipelineFactory(new AutobahnServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(9000)); + bootstrap.bind(new InetSocketAddress(port)); - System.out.println("Web Socket Server started on localhost:9000."); + System.out.println("Web Socket Server started at port " + port); + } + + public static void main(String[] args) { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 9000; + } + new AutobahnServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServerHandler.java b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java similarity index 97% rename from example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServerHandler.java rename to example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java index 6c7d9e2c5e..b1edbca325 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServerHandler.java +++ b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerHandler.java @@ -47,8 +47,8 @@ import io.netty.util.CharsetUtil; /** * Handles handshakes and messages */ -public class WebSocketServerHandler extends SimpleChannelUpstreamHandler { - private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandler.class); +public class AutobahnServerHandler extends SimpleChannelUpstreamHandler { + private static final InternalLogger logger = InternalLoggerFactory.getInstance(AutobahnServerHandler.class); private WebSocketServerHandshaker handshaker; diff --git a/example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServerPipelineFactory.java b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java similarity index 89% rename from example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServerPipelineFactory.java rename to example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java index 469f832bc6..44eea6cd97 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/autobahn/WebSocketServerPipelineFactory.java +++ b/example/src/main/java/io/netty/example/http/websocketx/autobahn/AutobahnServerPipelineFactory.java @@ -23,9 +23,7 @@ import io.netty.handler.codec.http.HttpChunkAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; -/** - */ -public class WebSocketServerPipelineFactory implements ChannelPipelineFactory { +public class AutobahnServerPipelineFactory implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. @@ -33,7 +31,7 @@ public class WebSocketServerPipelineFactory implements ChannelPipelineFactory { pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpChunkAggregator(65536)); pipeline.addLast("encoder", new HttpResponseEncoder()); - pipeline.addLast("handler", new WebSocketServerHandler()); + pipeline.addLast("handler", new AutobahnServerHandler()); return pipeline; } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/autobahn/package-info.java b/example/src/main/java/io/netty/example/http/websocketx/autobahn/package-info.java index 09b3632b4e..892442c725 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/autobahn/package-info.java +++ b/example/src/main/java/io/netty/example/http/websocketx/autobahn/package-info.java @@ -47,7 +47,7 @@ * } * * - *

10. Run WebSocketServer in this package + *

10. Run AutobahnServer in this package * *

11. Run the test python fuzzing_client.py. Note that the actual test case python code is * located in /usr/local/lib/python2.6/dist-packages/autobahn-0.4.3-py2.6.egg/autobahn/cases diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/App.java b/example/src/main/java/io/netty/example/http/websocketx/client/App.java deleted file mode 100644 index 9b899afc96..0000000000 --- a/example/src/main/java/io/netty/example/http/websocketx/client/App.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2011 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.example.http.websocketx.client; - -import java.net.URI; -import java.util.ArrayList; -import java.util.logging.ConsoleHandler; -import java.util.logging.Level; -import java.util.logging.Logger; - -import io.netty.buffer.ChannelBuffers; -import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; -import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; -import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; -import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketVersion; - -/** - * A HTTP client demo app - */ -public class App { - - public static void main(String[] args) throws Exception { - new App().runClient(); - } - - /** - * Send and receive some messages using a web socket client - * - * @throws Exception - */ - public void runClient() throws Exception { - - MyCallbackHandler callbackHandler = new MyCallbackHandler(); - WebSocketClientFactory factory = new WebSocketClientFactory(); - - // Connect with RFC 6455. 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, null); - - // Connect - System.out.println("WebSocket Client connecting"); - client.connect().awaitUninterruptibly(); - Thread.sleep(200); - - // Send 10 messages and wait for responses - System.out.println("WebSocket Client sending message"); - for (int i = 0; i < 10; i++) { - client.send(new TextWebSocketFrame("Message #" + i)); - } - Thread.sleep(1000); - - // Ping - only supported for V10 and up. - System.out.println("WebSocket Client sending ping"); - client.send(new PingWebSocketFrame(ChannelBuffers.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 }))); - Thread.sleep(1000); - - // Close - System.out.println("WebSocket Client sending close"); - client.send(new CloseWebSocketFrame()); - Thread.sleep(1000); - - // Disconnect - client.disconnect(); - } - - /** - * Our web socket callback handler for this app - */ - public static class MyCallbackHandler implements WebSocketCallback { - public boolean connected; - public ArrayList messagesReceived = new ArrayList(); - - public MyCallbackHandler() { - } - - @Override - public void onConnect(WebSocketClient client) { - System.out.println("WebSocket Client connected!"); - connected = true; - } - - @Override - public void onDisconnect(WebSocketClient client) { - System.out.println("WebSocket Client disconnected!"); - connected = false; - } - - @Override - public void onMessage(WebSocketClient client, WebSocketFrame frame) { - if (frame instanceof TextWebSocketFrame) { - TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; - System.out.println("WebSocket Client received message:" + textFrame.getText()); - messagesReceived.add(textFrame.getText()); - } else if (frame instanceof PongWebSocketFrame) { - System.out.println("WebSocket Client received pong"); - } else if (frame instanceof CloseWebSocketFrame) { - System.out.println("WebSocket Client received closing"); - } - } - - @Override - public void onError(Throwable t) { - System.out.println("WebSocket Client error " + t.toString()); - } - - } - -} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketCallback.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketCallback.java deleted file mode 100644 index ed64532ce0..0000000000 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketCallback.java +++ /dev/null @@ -1,67 +0,0 @@ -//The MIT License -// -//Copyright (c) 2009 Carl Bystršm -// -//Permission is hereby granted, free of charge, to any person obtaining a copy -//of this software and associated documentation files (the "Software"), to deal -//in the Software without restriction, including without limitation the rights -//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -//copies of the Software, and to permit persons to whom the Software is -//furnished to do so, subject to the following conditions: -// -//The above copyright notice and this permission notice shall be included in -//all copies or substantial portions of the Software. -// -//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -//THE SOFTWARE. - -package io.netty.example.http.websocketx.client; - -import io.netty.handler.codec.http.websocketx.WebSocketFrame; - -/** - * Copied from https://github.com/cgbystrom/netty-tools - * - * Callbacks for the {@link WebSocketClient}. Implement and get notified when events happen. - */ -public interface WebSocketCallback { - - /** - * Called when the client is connected to the server - * - * @param client - * Current client used to connect - */ - void onConnect(WebSocketClient client); - - /** - * Called when the client got disconnected from the server. - * - * @param client - * Current client that was disconnected - */ - void onDisconnect(WebSocketClient client); - - /** - * Called when a message arrives from the server. - * - * @param client - * Current client connected - * @param frame - * Data received from server - */ - void onMessage(WebSocketClient client, WebSocketFrame frame); - - /** - * Called when an unhandled errors occurs. - * - * @param t - * The causing error - */ - void onError(Throwable t); -} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java index 24064bb56b..58041cfdb1 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClient.java @@ -21,34 +21,116 @@ //THE SOFTWARE. package io.netty.example.http.websocketx.client; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.HashMap; +import java.util.concurrent.Executors; + +import io.netty.bootstrap.ClientBootstrap; +import io.netty.buffer.ChannelBuffers; +import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; -import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.ChannelPipelineFactory; +import io.netty.channel.Channels; +import io.netty.channel.socket.nio.NioClientSocketChannelFactory; +import io.netty.handler.codec.http.HttpRequestEncoder; +import io.netty.handler.codec.http.HttpResponseDecoder; +import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; +import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; +import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; +import io.netty.handler.codec.http.websocketx.WebSocketVersion; -/** - * Copied from https://github.com/cgbystrom/netty-tools - */ -public interface WebSocketClient { +public class WebSocketClient { - /** - * Connect to server Host and port is setup by the factory. - * - * @return Connect future. Fires when connected. - */ - ChannelFuture connect(); + private final URI uri; + + public WebSocketClient(URI uri) { + this.uri = uri; + } + + public void run() throws Exception { + ClientBootstrap bootstrap = + new ClientBootstrap( + new NioClientSocketChannelFactory( + Executors.newCachedThreadPool(), + Executors.newCachedThreadPool())); - /** - * Disconnect from the server - * - * @return Disconnect future. Fires when disconnected. - */ - ChannelFuture disconnect(); + String protocol = uri.getScheme(); + if (!protocol.equals("ws")) { + throw new IllegalArgumentException("Unsupported protocol: " + protocol); + } - /** - * Send data to server - * - * @param frame - * Data for sending - * @return Write future. Will fire when the data is sent. - */ - ChannelFuture send(WebSocketFrame frame); + HashMap customHeaders = new HashMap(); + 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. + final WebSocketClientHandshaker handshaker = + new WebSocketClientHandshakerFactory().newHandshaker( + uri, WebSocketVersion.V13, null, false, 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 + // HttpResponseDecoder. + pipeline.addLast("decoder", new HttpResponseDecoder()); + + pipeline.addLast("encoder", new HttpRequestEncoder()); + pipeline.addLast("ws-handler", new WebSocketClientHandler(handshaker)); + return pipeline; + } + }); + + // Connect + System.out.println("WebSocket Client connecting"); + ChannelFuture future = + bootstrap.connect( + new InetSocketAddress(uri.getHost(), uri.getPort())); + future.awaitUninterruptibly(); + + Channel ch = future.getChannel(); + + handshaker.performOpeningHandshake(ch); + + Thread.sleep(1000); + + // Send 10 messages and wait for responses + System.out.println("WebSocket Client sending message"); + for (int i = 0; i < 10; i++) { + ch.write(new TextWebSocketFrame("Message #" + i)); + } + Thread.sleep(1000); + + // Ping + System.out.println("WebSocket Client sending ping"); + ch.write(new PingWebSocketFrame(ChannelBuffers.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 }))); + Thread.sleep(1000); + + // Close + System.out.println("WebSocket Client sending close"); + ch.write(new CloseWebSocketFrame()); + + // WebSocketClientHandler will close the connection when the server + // responds to the CloseWebSocketFrame. + ch.getCloseFuture().awaitUninterruptibly(); + + bootstrap.releaseExternalResources(); + } + + public static void main(String[] args) throws Exception { + URI uri; + if (args.length > 0) { + uri = new URI(args[0]); + } else { + uri = new URI("ws://localhost:8080/websocket"); + } + new WebSocketClient(uri).run(); + } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientFactory.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientFactory.java deleted file mode 100644 index 396dcb6829..0000000000 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientFactory.java +++ /dev/null @@ -1,92 +0,0 @@ -//The MIT License -// -//Copyright (c) 2009 Carl Bystršm -// -//Permission is hereby granted, free of charge, to any person obtaining a copy -//of this software and associated documentation files (the "Software"), to deal -//in the Software without restriction, including without limitation the rights -//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -//copies of the Software, and to permit persons to whom the Software is -//furnished to do so, subject to the following conditions: -// -//The above copyright notice and this permission notice shall be included in -//all copies or substantial portions of the Software. -// -//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -//THE SOFTWARE. - -package io.netty.example.http.websocketx.client; - -import io.netty.bootstrap.ClientBootstrap; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.ChannelPipelineFactory; -import io.netty.channel.Channels; -import io.netty.channel.socket.nio.NioClientSocketChannelFactory; -import io.netty.handler.codec.http.HttpRequestEncoder; -import io.netty.handler.codec.http.HttpResponseDecoder; -import io.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. - */ -public class WebSocketClientFactory { - - private final NioClientSocketChannelFactory socketChannelFactory = new NioClientSocketChannelFactory( - Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); - - /** - * Create a new WebSocket client. - * - * @param url - * URL to connect to. - * @param version - * Web Socket version to support - * @param callback - * Callback interface to receive events - * @param customHeaders - * custom HTTP headers to pass during the handshake - * @return A WebSocket client. Call {@link WebSocketClient#connect()} to connect. - */ - public WebSocketClient newClient(final URI url, final WebSocketVersion version, final WebSocketCallback callback, - Map customHeaders) { - ClientBootstrap bootstrap = new ClientBootstrap(socketChannelFactory); - - String protocol = url.getScheme(); - if (!protocol.equals("ws") && !protocol.equals("wss")) { - throw new IllegalArgumentException("Unsupported protocol: " + protocol); - } - - final WebSocketClientHandler clientHandler = new WebSocketClientHandler(bootstrap, url, version, callback, - customHeaders); - - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - - @Override - public ChannelPipeline getPipeline() throws Exception { - ChannelPipeline pipeline = Channels.pipeline(); - - // 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("ws-handler", clientHandler); - return pipeline; - } - }); - - return clientHandler; - } -} diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java index b23527cad2..063fd7a6a8 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java @@ -22,68 +22,39 @@ package io.netty.example.http.websocketx.client; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.Map; - -import io.netty.bootstrap.ClientBootstrap; import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelStateEvent; import io.netty.channel.ExceptionEvent; import io.netty.channel.MessageEvent; import io.netty.channel.SimpleChannelUpstreamHandler; import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; -import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.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. - */ -public class WebSocketClientHandler extends SimpleChannelUpstreamHandler implements WebSocketClient { +public class WebSocketClientHandler extends SimpleChannelUpstreamHandler { - private final ClientBootstrap bootstrap; - private URI url; - private final WebSocketCallback callback; - private Channel channel; - private WebSocketClientHandshaker handshaker; - private final WebSocketVersion version; - private Map customHeaders; + private final WebSocketClientHandshaker handshaker; - public WebSocketClientHandler(ClientBootstrap bootstrap, URI url, WebSocketVersion version, - WebSocketCallback callback, Map 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, customHeaders); - handshaker.performOpeningHandshake(channel); + public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { + this.handshaker = handshaker; } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { - callback.onDisconnect(this); + System.out.println("WebSocket Client disconnected!"); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + Channel ch = ctx.getChannel(); if (!handshaker.isOpeningHandshakeCompleted()) { - handshaker.performClosingHandshake(ctx.getChannel(), (HttpResponse) e.getMessage()); - callback.onConnect(this); + handshaker.performClosingHandshake(ch, (HttpResponse) e.getMessage()); + System.out.println("WebSocket Client connected!"); return; } @@ -94,36 +65,21 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme } WebSocketFrame frame = (WebSocketFrame) e.getMessage(); - callback.onMessage(this, frame); + if (frame instanceof TextWebSocketFrame) { + TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; + System.out.println("WebSocket Client received message: " + textFrame.getText()); + } else if (frame instanceof PongWebSocketFrame) { + System.out.println("WebSocket Client received pong"); + } else if (frame instanceof CloseWebSocketFrame) { + System.out.println("WebSocket Client received closing"); + ch.close(); + } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { final Throwable t = e.getCause(); - callback.onError(t); + t.printStackTrace(); e.getChannel().close(); } - - @Override - public ChannelFuture connect() { - return bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort())); - } - - @Override - public ChannelFuture disconnect() { - return channel.close(); - } - - @Override - public ChannelFuture send(WebSocketFrame frame) { - return channel.write(frame); - } - - public URI getUrl() { - return url; - } - - public void setUrl(URI url) { - this.url = url; - } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java b/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java index b903874eaf..013ff4941b 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java +++ b/example/src/main/java/io/netty/example/http/websocketx/client/package-info.java @@ -16,9 +16,8 @@ /** *

This is an example web service client. - *

To run this example, you must first start - * io.netty.example.http.websocketx.server.WebSocketServer - *

Next, run io.netty.example.http.websocketx.client.App. + *

To run this example, you must first start {@link WebSocketServer} and + * then {@link WebSocketClient}. */ package io.netty.example.http.websocketx.client; diff --git a/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServer.java b/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServer.java index 3580fd68db..b2899692dd 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServer.java +++ b/example/src/main/java/io/netty/example/http/websocketx/server/WebSocketServer.java @@ -43,12 +43,14 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; * */ public class WebSocketServer { - public static void main(String[] args) { - ConsoleHandler ch = new ConsoleHandler(); - ch.setLevel(Level.FINE); - Logger.getLogger("").addHandler(ch); - Logger.getLogger("").setLevel(Level.FINE); + private final int port; + + public WebSocketServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); @@ -57,9 +59,19 @@ public class WebSocketServer { bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); - System.out - .println("Web Socket Server started on 8080. Open your browser and navigate to http://localhost:8080/"); + System.out.println("Web socket server started at port " + port + '.'); + System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); + } + + public static void main(String[] args) { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new WebSocketServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/http/websocketx/sslserver/WebSocketSslServer.java b/example/src/main/java/io/netty/example/http/websocketx/sslserver/WebSocketSslServer.java index c491b43235..def9595f90 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/sslserver/WebSocketSslServer.java +++ b/example/src/main/java/io/netty/example/http/websocketx/sslserver/WebSocketSslServer.java @@ -43,11 +43,35 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; * */ public class WebSocketSslServer { + + private final int port; + + public WebSocketSslServer(int port) { + this.port = port; + } + + public void run() { + // Configure the server. + ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( + Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); + + // Set up the event pipeline factory. + bootstrap.setPipelineFactory(new WebSocketSslServerPipelineFactory()); + + // Bind and start to accept incoming connections. + bootstrap.bind(new InetSocketAddress(port)); + + System.out.println("Web socket server started at port " + port + '.'); + System.out.println("Open your browser and navigate to https://localhost:" + port + '/'); + } + public static void main(String[] args) { - ConsoleHandler ch = new ConsoleHandler(); - ch.setLevel(Level.FINE); - Logger.getLogger("").addHandler(ch); - Logger.getLogger("").setLevel(Level.FINE); + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8443; + } String keyStoreFilePath = System.getProperty("keystore.file.path"); if (keyStoreFilePath == null || keyStoreFilePath.isEmpty()) { @@ -61,17 +85,6 @@ public class WebSocketSslServer { System.exit(1); } - // Configure the server. - ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( - Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); - - // Set up the event pipeline factory. - bootstrap.setPipelineFactory(new WebSocketSslServerPipelineFactory()); - - // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8081)); - - System.out - .println("Web Socket Server started on 8081. Open your browser and navigate to https://localhost:8081/"); + new WebSocketSslServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/local/LocalExample.java b/example/src/main/java/io/netty/example/local/LocalExample.java index d853f6094b..50eaa63639 100644 --- a/example/src/main/java/io/netty/example/local/LocalExample.java +++ b/example/src/main/java/io/netty/example/local/LocalExample.java @@ -16,6 +16,7 @@ package io.netty.example.local; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import io.netty.bootstrap.ClientBootstrap; @@ -34,9 +35,16 @@ import io.netty.handler.logging.LoggingHandler; import io.netty.logging.InternalLogLevel; public class LocalExample { - public static void main(String[] args) throws Exception { + + private final String port; + + public LocalExample(String port) { + this.port = port; + } + + public void run() throws IOException { // Address to bind on / connect to. - LocalAddress socketAddress = new LocalAddress("1"); + LocalAddress socketAddress = new LocalAddress(port); // Configure the server. ServerBootstrap sb = new ServerBootstrap( @@ -55,7 +63,6 @@ public class LocalExample { // Set up the client-side pipeline factory. cb.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( new StringDecoder(), @@ -95,4 +102,8 @@ public class LocalExample { cb.releaseExternalResources(); sb.releaseExternalResources(); } + + public static void main(String[] args) throws Exception { + new LocalExample("1").run(); + } } diff --git a/example/src/main/java/io/netty/example/local/LocalExampleMultthreaded.java b/example/src/main/java/io/netty/example/local/LocalExampleMultithreaded.java similarity index 92% rename from example/src/main/java/io/netty/example/local/LocalExampleMultthreaded.java rename to example/src/main/java/io/netty/example/local/LocalExampleMultithreaded.java index f05219abc1..0a4e68f234 100644 --- a/example/src/main/java/io/netty/example/local/LocalExampleMultthreaded.java +++ b/example/src/main/java/io/netty/example/local/LocalExampleMultithreaded.java @@ -32,10 +32,16 @@ import io.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import io.netty.handler.logging.LoggingHandler; import io.netty.logging.InternalLogLevel; -public class LocalExampleMultthreaded { +public class LocalExampleMultithreaded { - public static void main(String[] args) throws Exception { - LocalAddress socketAddress = new LocalAddress("1"); + private final String port; + + public LocalExampleMultithreaded(String port) { + this.port = port; + } + + public void run() { + LocalAddress socketAddress = new LocalAddress(port); OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor( @@ -52,7 +58,6 @@ public class LocalExampleMultthreaded { new DefaultLocalClientChannelFactory()); cb.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( new StringDecoder(), @@ -93,4 +98,8 @@ public class LocalExampleMultthreaded { sb.releaseExternalResources(); eventExecutor.shutdownNow(); } + + public static void main(String[] args) throws Exception { + new LocalExampleMultithreaded("1").run(); + } } diff --git a/example/src/main/java/io/netty/example/localtime/LocalTimeClient.java b/example/src/main/java/io/netty/example/localtime/LocalTimeClient.java index 58ae89548c..4273fb6edb 100644 --- a/example/src/main/java/io/netty/example/localtime/LocalTimeClient.java +++ b/example/src/main/java/io/netty/example/localtime/LocalTimeClient.java @@ -33,21 +33,18 @@ import io.netty.channel.socket.nio.NioClientSocketChannelFactory; */ public class LocalTimeClient { - public static void main(String[] args) throws Exception { - // Print usage if necessary. - if (args.length < 3) { - printUsage(); - return; - } + private final String host; + private final int port; + private final Collection cities; - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); - Collection cities = parseCities(args, 2); - if (cities == null) { - return; - } + public LocalTimeClient(String host, int port, Collection cities) { + this.host = host; + this.port = port; + this.cities = new ArrayList(); + this.cities.addAll(cities); + } + public void run() { // Set up. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( @@ -84,6 +81,24 @@ public class LocalTimeClient { } } + public static void main(String[] args) throws Exception { + // Print usage if necessary. + if (args.length < 3) { + printUsage(); + return; + } + + // Parse options. + String host = args[0]; + int port = Integer.parseInt(args[1]); + Collection cities = parseCities(args, 2); + if (cities == null) { + return; + } + + new LocalTimeClient(host, port, cities).run(); + } + private static void printUsage() { System.err.println( "Usage: " + LocalTimeClient.class.getSimpleName() + diff --git a/example/src/main/java/io/netty/example/localtime/LocalTimeServer.java b/example/src/main/java/io/netty/example/localtime/LocalTimeServer.java index 168d5b3a11..11aad21b06 100644 --- a/example/src/main/java/io/netty/example/localtime/LocalTimeServer.java +++ b/example/src/main/java/io/netty/example/localtime/LocalTimeServer.java @@ -27,7 +27,13 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class LocalTimeServer { - public static void main(String[] args) throws Exception { + private final int port; + + public LocalTimeServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -38,6 +44,16 @@ public class LocalTimeServer { bootstrap.setPipelineFactory(new LocalTimeServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new LocalTimeServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/objectecho/ObjectEchoClient.java b/example/src/main/java/io/netty/example/objectecho/ObjectEchoClient.java index dc36e720c7..a4ff2b5a41 100644 --- a/example/src/main/java/io/netty/example/objectecho/ObjectEchoClient.java +++ b/example/src/main/java/io/netty/example/objectecho/ObjectEchoClient.java @@ -32,6 +32,37 @@ import io.netty.handler.codec.serialization.ObjectEncoder; */ public class ObjectEchoClient { + private final String host; + private final int port; + private final int firstMessageSize; + + public ObjectEchoClient(String host, int port, int firstMessageSize) { + this.host = host; + this.port = port; + this.firstMessageSize = firstMessageSize; + } + + public void run() { + // Configure the client. + ClientBootstrap bootstrap = new ClientBootstrap( + new NioClientSocketChannelFactory( + Executors.newCachedThreadPool(), + Executors.newCachedThreadPool())); + + // Set up the pipeline factory. + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() throws Exception { + return Channels.pipeline( + new ObjectEncoder(), + new ObjectDecoder(), + new ObjectEchoClientHandler(firstMessageSize)); + } + }); + + // Start the connection attempt. + bootstrap.connect(new InetSocketAddress(host, port)); + } + public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length < 2 || args.length > 3) { @@ -52,24 +83,6 @@ public class ObjectEchoClient { firstMessageSize = 256; } - // Configure the client. - ClientBootstrap bootstrap = new ClientBootstrap( - new NioClientSocketChannelFactory( - Executors.newCachedThreadPool(), - Executors.newCachedThreadPool())); - - // Set up the pipeline factory. - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override - public ChannelPipeline getPipeline() throws Exception { - return Channels.pipeline( - new ObjectEncoder(), - new ObjectDecoder(), - new ObjectEchoClientHandler(firstMessageSize)); - } - }); - - // Start the connection attempt. - bootstrap.connect(new InetSocketAddress(host, port)); + new ObjectEchoClient(host, port, firstMessageSize).run(); } } diff --git a/example/src/main/java/io/netty/example/objectecho/ObjectEchoServer.java b/example/src/main/java/io/netty/example/objectecho/ObjectEchoServer.java index c1915b9180..e30ebd3821 100644 --- a/example/src/main/java/io/netty/example/objectecho/ObjectEchoServer.java +++ b/example/src/main/java/io/netty/example/objectecho/ObjectEchoServer.java @@ -32,7 +32,13 @@ import io.netty.handler.codec.serialization.ObjectEncoder; */ public class ObjectEchoServer { - public static void main(String[] args) throws Exception { + private final int port; + + public ObjectEchoServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -41,7 +47,6 @@ public class ObjectEchoServer { // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( new ObjectEncoder(), @@ -51,6 +56,16 @@ public class ObjectEchoServer { }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new ObjectEchoServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/portunification/PortUnificationServer.java b/example/src/main/java/io/netty/example/portunification/PortUnificationServer.java index 093b6c6214..1070490feb 100644 --- a/example/src/main/java/io/netty/example/portunification/PortUnificationServer.java +++ b/example/src/main/java/io/netty/example/portunification/PortUnificationServer.java @@ -33,7 +33,13 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class PortUnificationServer { - public static void main(String[] args) throws Exception { + private final int port; + + public PortUnificationServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -42,13 +48,22 @@ public class PortUnificationServer { // Set up the event pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new PortUnificationServerHandler()); } }); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new PortUnificationServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/proxy/HexDumpProxy.java b/example/src/main/java/io/netty/example/proxy/HexDumpProxy.java index 7bf2138e7e..44e8d5dc46 100644 --- a/example/src/main/java/io/netty/example/proxy/HexDumpProxy.java +++ b/example/src/main/java/io/netty/example/proxy/HexDumpProxy.java @@ -26,23 +26,6 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; public class HexDumpProxy { - public static void main(String[] args) throws Exception { - // Validate command line options. - if (args.length != 3) { - System.err.println( - "Usage: " + HexDumpProxy.class.getSimpleName() + - " "); - return; - } - - // Parse command line options. - int localPort = Integer.parseInt(args[0]); - String remoteHost = args[1]; - int remotePort = Integer.parseInt(args[2]); - - new HexDumpProxy(localPort, remoteHost, remotePort).run(); - } - private final int localPort; private final String remoteHost; private final int remotePort; @@ -73,4 +56,21 @@ public class HexDumpProxy { // Start up the server. sb.bind(new InetSocketAddress(localPort)); } + + public static void main(String[] args) throws Exception { + // Validate command line options. + if (args.length != 3) { + System.err.println( + "Usage: " + HexDumpProxy.class.getSimpleName() + + " "); + return; + } + + // Parse command line options. + int localPort = Integer.parseInt(args[0]); + String remoteHost = args[1]; + int remotePort = Integer.parseInt(args[2]); + + new HexDumpProxy(localPort, remoteHost, remotePort).run(); + } } diff --git a/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentClient.java b/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentClient.java index 47bd87beca..986bb2b701 100644 --- a/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentClient.java +++ b/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentClient.java @@ -38,7 +38,13 @@ import io.netty.util.CharsetUtil; */ public class QuoteOfTheMomentClient { - public static void main(String[] args) throws Exception { + private final int port; + + public QuoteOfTheMomentClient(int port) { + this.port = port; + } + + public void run() { DatagramChannelFactory f = new NioDatagramChannelFactory(Executors.newCachedThreadPool()); @@ -46,7 +52,6 @@ public class QuoteOfTheMomentClient { // Configure the pipeline factory. b.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( new StringEncoder(CharsetUtil.ISO_8859_1), @@ -75,7 +80,7 @@ public class QuoteOfTheMomentClient { DatagramChannel c = (DatagramChannel) b.bind(new InetSocketAddress(0)); // Broadcast the QOTM request to port 8080. - c.write("QOTM?", new InetSocketAddress("255.255.255.255", 8080)); + c.write("QOTM?", new InetSocketAddress("255.255.255.255", port)); // QuoteOfTheMomentClientHandler will close the DatagramChannel when a // response is received. If the channel is not closed within 5 seconds, @@ -87,4 +92,14 @@ public class QuoteOfTheMomentClient { f.releaseExternalResources(); } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new QuoteOfTheMomentClient(port).run(); + } } diff --git a/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentServer.java b/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentServer.java index 74cade2f00..fc035b8f83 100644 --- a/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentServer.java +++ b/example/src/main/java/io/netty/example/qotm/QuoteOfTheMomentServer.java @@ -37,7 +37,13 @@ import io.netty.util.CharsetUtil; */ public class QuoteOfTheMomentServer { - public static void main(String[] args) throws Exception { + private final int port; + + public QuoteOfTheMomentServer(int port) { + this.port = port; + } + + public void run() { DatagramChannelFactory f = new NioDatagramChannelFactory(Executors.newCachedThreadPool()); @@ -45,7 +51,6 @@ public class QuoteOfTheMomentServer { // Configure the pipeline factory. b.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( new StringEncoder(CharsetUtil.ISO_8859_1), @@ -54,7 +59,7 @@ public class QuoteOfTheMomentServer { } }); - // Server doesn't need to enable broadcast to listen to a broadcast. + // Enable broadcast b.setOption("broadcast", "false"); // Allow packets as large as up to 1024 bytes (default is 768). @@ -72,6 +77,16 @@ public class QuoteOfTheMomentServer { new FixedReceiveBufferSizePredictorFactory(1024)); // Bind to the port and start the service. - b.bind(new InetSocketAddress(8080)); + b.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new QuoteOfTheMomentServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/securechat/SecureChatClient.java b/example/src/main/java/io/netty/example/securechat/SecureChatClient.java index 3d137f9d5d..334c846855 100644 --- a/example/src/main/java/io/netty/example/securechat/SecureChatClient.java +++ b/example/src/main/java/io/netty/example/securechat/SecureChatClient.java @@ -16,6 +16,7 @@ package io.netty.example.securechat; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.concurrent.Executors; @@ -31,19 +32,15 @@ import io.netty.example.telnet.TelnetClient; */ public class SecureChatClient { - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 2) { - System.err.println( - "Usage: " + SecureChatClient.class.getSimpleName() + - " "); - return; - } + private final String host; + private final int port; - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); + public SecureChatClient(String host, int port) { + this.host = host; + this.port = port; + } + public void run() throws IOException { // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( @@ -96,4 +93,20 @@ public class SecureChatClient { // Shut down all thread pools to exit. bootstrap.releaseExternalResources(); } + + public static void main(String[] args) throws Exception { + // Print usage if no argument is specified. + if (args.length != 2) { + System.err.println( + "Usage: " + SecureChatClient.class.getSimpleName() + + " "); + return; + } + + // Parse options. + String host = args[0]; + int port = Integer.parseInt(args[1]); + + new SecureChatClient(host, port).run(); + } } diff --git a/example/src/main/java/io/netty/example/securechat/SecureChatServer.java b/example/src/main/java/io/netty/example/securechat/SecureChatServer.java index cce842afd7..f93274e3ea 100644 --- a/example/src/main/java/io/netty/example/securechat/SecureChatServer.java +++ b/example/src/main/java/io/netty/example/securechat/SecureChatServer.java @@ -27,7 +27,13 @@ import io.netty.example.telnet.TelnetServer; */ public class SecureChatServer { - public static void main(String[] args) throws Exception { + private final int port; + + public SecureChatServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -38,6 +44,16 @@ public class SecureChatServer { bootstrap.setPipelineFactory(new SecureChatServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8443; + } + new SecureChatServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/telnet/TelnetClient.java b/example/src/main/java/io/netty/example/telnet/TelnetClient.java index 97dd175b55..28c676b7ef 100644 --- a/example/src/main/java/io/netty/example/telnet/TelnetClient.java +++ b/example/src/main/java/io/netty/example/telnet/TelnetClient.java @@ -16,6 +16,7 @@ package io.netty.example.telnet; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.concurrent.Executors; @@ -30,19 +31,15 @@ import io.netty.channel.socket.nio.NioClientSocketChannelFactory; */ public class TelnetClient { - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 2) { - System.err.println( - "Usage: " + TelnetClient.class.getSimpleName() + - " "); - return; - } + private final String host; + private final int port; - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); + public TelnetClient(String host, int port) { + this.host = host; + this.port = port; + } + public void run() throws IOException { // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( @@ -95,4 +92,20 @@ public class TelnetClient { // Shut down all thread pools to exit. bootstrap.releaseExternalResources(); } + + public static void main(String[] args) throws Exception { + // Print usage if no argument is specified. + if (args.length != 2) { + System.err.println( + "Usage: " + TelnetClient.class.getSimpleName() + + " "); + return; + } + + // Parse options. + String host = args[0]; + int port = Integer.parseInt(args[1]); + + new TelnetClient(host, port).run(); + } } diff --git a/example/src/main/java/io/netty/example/telnet/TelnetServer.java b/example/src/main/java/io/netty/example/telnet/TelnetServer.java index 633b88df5e..4e2aa23e16 100644 --- a/example/src/main/java/io/netty/example/telnet/TelnetServer.java +++ b/example/src/main/java/io/netty/example/telnet/TelnetServer.java @@ -26,7 +26,13 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory; */ public class TelnetServer { - public static void main(String[] args) throws Exception { + private final int port; + + public TelnetServer(int port) { + this.port = port; + } + + public void run() { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( @@ -37,6 +43,16 @@ public class TelnetServer { bootstrap.setPipelineFactory(new TelnetServerPipelineFactory()); // Bind and start to accept incoming connections. - bootstrap.bind(new InetSocketAddress(8080)); + bootstrap.bind(new InetSocketAddress(port)); + } + + public static void main(String[] args) throws Exception { + int port; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } else { + port = 8080; + } + new TelnetServer(port).run(); } } diff --git a/example/src/main/java/io/netty/example/uptime/UptimeClient.java b/example/src/main/java/io/netty/example/uptime/UptimeClient.java index d63b981278..1984a61c91 100644 --- a/example/src/main/java/io/netty/example/uptime/UptimeClient.java +++ b/example/src/main/java/io/netty/example/uptime/UptimeClient.java @@ -42,19 +42,15 @@ public class UptimeClient { // Reconnect when the server sends nothing for 10 seconds. private static final int READ_TIMEOUT = 10; - public static void main(String[] args) throws Exception { - // Print usage if no argument is specified. - if (args.length != 2) { - System.err.println( - "Usage: " + UptimeClient.class.getSimpleName() + - " "); - return; - } + private final String host; + private final int port; - // Parse options. - String host = args[0]; - int port = Integer.parseInt(args[1]); + public UptimeClient(String host, int port) { + this.host = host; + this.port = port; + } + public void run() { // Initialize the timer that schedules subsequent reconnection attempts. final Timer timer = new HashedWheelTimer(); @@ -72,7 +68,6 @@ public class UptimeClient { private final ChannelHandler uptimeHandler = new UptimeClientHandler(bootstrap, timer); - @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline( timeoutHandler, uptimeHandler); @@ -86,4 +81,20 @@ public class UptimeClient { // UptimeClientHandler. bootstrap.connect(); } + + public static void main(String[] args) throws Exception { + // Print usage if no argument is specified. + if (args.length != 2) { + System.err.println( + "Usage: " + UptimeClient.class.getSimpleName() + + " "); + return; + } + + // Parse options. + String host = args[0]; + int port = Integer.parseInt(args[1]); + + new UptimeClient(host, port).run(); + } } diff --git a/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java b/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java index d934a8e1ec..096e575db6 100644 --- a/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java +++ b/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java @@ -57,7 +57,6 @@ public class UptimeClientHandler extends SimpleChannelUpstreamHandler { public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) { println("Sleeping for: " + UptimeClient.RECONNECT_DELAY + "s"); timer.newTimeout(new TimerTask() { - @Override public void run(Timeout timeout) throws Exception { println("Reconnecting to: " + getRemoteAddress()); bootstrap.connect();