View Javadoc
1   /*
2    * Copyright 2020 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.example.haproxy;
18  
19  import io.netty.bootstrap.Bootstrap;
20  import io.netty.buffer.Unpooled;
21  import io.netty.channel.Channel;
22  import io.netty.channel.EventLoopGroup;
23  import io.netty.channel.nio.NioEventLoopGroup;
24  import io.netty.channel.socket.nio.NioSocketChannel;
25  import io.netty.handler.codec.haproxy.HAProxyCommand;
26  import io.netty.handler.codec.haproxy.HAProxyMessage;
27  import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
28  import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol;
29  import io.netty.util.CharsetUtil;
30  
31  import static io.netty.example.haproxy.HAProxyServer.*;
32  
33  public final class HAProxyClient {
34  
35      private static final String HOST = System.getProperty("host", "127.0.0.1");
36  
37      public static void main(String[] args) throws Exception {
38          EventLoopGroup group = new NioEventLoopGroup();
39          try {
40              Bootstrap b = new Bootstrap();
41              b.group(group)
42               .channel(NioSocketChannel.class)
43               .handler(new HAProxyHandler());
44  
45              // Start the connection attempt.
46              Channel ch = b.connect(HOST, PORT).sync().channel();
47  
48              HAProxyMessage message = new HAProxyMessage(
49                      HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4,
50                      "127.0.0.1", "127.0.0.2", 8000, 9000);
51  
52              ch.writeAndFlush(message).sync();
53              ch.writeAndFlush(Unpooled.copiedBuffer("Hello World!", CharsetUtil.US_ASCII)).sync();
54              ch.writeAndFlush(Unpooled.copiedBuffer("Bye now!", CharsetUtil.US_ASCII)).sync();
55              ch.close().sync();
56          } finally {
57              group.shutdownGracefully();
58          }
59      }
60  }