01.public class MessageClient {
02.
03. public static void main(String[] args) throws Exception {
04. // Parse options.
05. String host = "127.0.0.1";
06. int port = 8080;
07. // Configure the client.
08. ClientBootstrap bootstrap = new ClientBootstrap(
09. new NioClientSocketChannelFactory(
10. Executors.newCachedThreadPool(),
11. Executors.newCachedThreadPool()));
12. // Set up the event pipeline factory.
13. bootstrap.setPipelineFactory(new MessageClientPipelineFactory());
14. // Start the connection attempt.
15. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
16. // Wait until the connection is closed or the connection attempt fails.
17. future.getChannel().getCloseFuture().awaitUninterruptibly();
18. // Shut down thread pools to exit.
19. bootstrap.releaseExternalResources();
20. }
21.}
01.public class MessageClientPipelineFactory implements
02. ChannelPipelineFactory {
03.
04. public ChannelPipeline getPipeline() throws Exception {
05. ChannelPipeline pipeline = pipeline();
06.
07. pipeline.addLast("decoder", new MessageDecoder());
08. pipeline.addLast("encoder", new MessageEncoder());
09. pipeline.addLast("handler", new MessageClientHandler());
10.
11. return pipeline;
12. }
02.public class MessageClientHandler extends SimpleChannelUpstreamHandler {
03.
04. private static final Logger logger = Logger.getLogger(
05. MessageClientHandler.class.getName());
06.
07.
08. @Override
09. public void channelConnected(
10. ChannelHandlerContext ctx, ChannelStateEvent e) {
11. String message = "hello kafka0102";
12. e.getChannel().write(message);
13. }
14.
15. @Override
16. public void messageReceived(
17. ChannelHandlerContext ctx, MessageEvent e) {
18. // Send back the received message to the remote peer.
19. System.err.println("messageReceived send message "+e.getMessage());
20. try {
21. Thread.sleep(1000*3);
22. } catch (Exception ex) {
23. ex.printStackTrace();
24. }
25. e.getChannel().write(e.getMessage());
26. }
27.
28. @Override
29. public void exceptionCaught(
30. ChannelHandlerContext ctx, ExceptionEvent e) {
31. // Close the connection when an exception is raised.
32. logger.log(
33. Level.WARNING,
34. "Unexpected exception from downstream.",
35. e.getCause());
36. e.getChannel().close();
37. }
38.}
需要 NETTY的JAR包,然后看看这个例子。