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.MultiThreadIoEventLoopGroup;
24  import io.netty.channel.nio.NioIoHandler;
25  import io.netty.channel.socket.nio.NioSocketChannel;
26  import io.netty.handler.codec.haproxy.HAProxyCommand;
27  import io.netty.handler.codec.haproxy.HAProxyMessage;
28  import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
29  import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol;
30  import io.netty.util.CharsetUtil;
31  
32  import static io.netty.example.haproxy.HAProxyServer.*;
33  
34  public final class HAProxyClient {
35  
36      private static final String HOST = System.getProperty("host", "127.0.0.1");
37  
38      public static void main(String[] args) throws Exception {
39          EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
40          try {
41              Bootstrap b = new Bootstrap();
42              b.group(group)
43               .channel(NioSocketChannel.class)
44               .handler(new HAProxyHandler());
45  
46              // Start the connection attempt.
47              Channel ch = b.connect(HOST, PORT).sync().channel();
48  
49              HAProxyMessage message = new HAProxyMessage(
50                      HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4,
51                      "127.0.0.1", "127.0.0.2", 8000, 9000);
52  
53              ch.writeAndFlush(message).sync();
54              ch.writeAndFlush(Unpooled.copiedBuffer("Hello World!", CharsetUtil.US_ASCII)).sync();
55              ch.writeAndFlush(Unpooled.copiedBuffer("Bye now!", CharsetUtil.US_ASCII)).sync();
56              ch.close().sync();
57          } finally {
58              group.shutdownGracefully();
59          }
60      }
61  }