2cdd97c9f90994a47472439a9320ad151a3a92b6
[netconf.git] / netconf / netconf-ssh / src / test / java / org / opendaylight / netconf / netty / EchoClient.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.netconf.netty;
10
11 import io.netty.bootstrap.Bootstrap;
12 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelHandler;
14 import io.netty.channel.ChannelInitializer;
15 import io.netty.channel.EventLoopGroup;
16 import io.netty.channel.local.LocalAddress;
17 import io.netty.channel.local.LocalChannel;
18 import io.netty.channel.nio.NioEventLoopGroup;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * Sends one message when a connection is open and echoes back any received
24  * data to the server.  Simply put, the echo client initiates the ping-pong
25  * traffic between the echo client and server by sending the first message to
26  * the server.
27  */
28 public class EchoClient extends Thread {
29     private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
30
31
32     private final ChannelInitializer<LocalChannel> channelInitializer;
33
34
35     public EchoClient(final ChannelHandler clientHandler) {
36         channelInitializer = new ChannelInitializer<LocalChannel>() {
37             @Override
38             public void initChannel(LocalChannel ch) throws Exception {
39                 ch.pipeline().addLast(clientHandler);
40             }
41         };
42     }
43
44     public EchoClient(ChannelInitializer<LocalChannel> channelInitializer) {
45         this.channelInitializer = channelInitializer;
46     }
47
48     @SuppressWarnings("checkstyle:IllegalCatch")
49     @Override
50     public void run() {
51         // Configure the client.
52         EventLoopGroup group = new NioEventLoopGroup();
53         try {
54             Bootstrap bootstrap = new Bootstrap();
55
56             bootstrap.group(group)
57                     .channel(LocalChannel.class)
58                     .handler(channelInitializer);
59
60             // Start the client.
61             LocalAddress localAddress = new LocalAddress("foo");
62             ChannelFuture future = bootstrap.connect(localAddress).sync();
63
64             // Wait until the connection is closed.
65             future.channel().closeFuture().sync();
66         } catch (Exception e) {
67             LOG.error("Error in client", e);
68             throw new RuntimeException("Error in client", e);
69         } finally {
70             // Shut down the event loop to terminate all threads.
71             LOG.info("Client is shutting down");
72             group.shutdownGracefully();
73         }
74     }
75 }