2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.ssh;
10 import io.netty.bootstrap.Bootstrap;
11 import io.netty.channel.ChannelFuture;
12 import io.netty.channel.ChannelHandler;
13 import io.netty.channel.ChannelInitializer;
14 import io.netty.channel.EventLoopGroup;
15 import io.netty.channel.local.LocalAddress;
16 import io.netty.channel.local.LocalChannel;
17 import io.netty.channel.nio.NioEventLoopGroup;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 * Sends one message when a connection is open and echoes back any received
23 * data to the server. Simply put, the echo client initiates the ping-pong
24 * traffic between the echo client and server by sending the first message to
27 public class EchoClient extends Thread {
28 private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
30 private final ChannelInitializer<LocalChannel> channelInitializer;
32 public EchoClient(final ChannelHandler clientHandler) {
33 channelInitializer = new ChannelInitializer<>() {
35 public void initChannel(final LocalChannel ch) {
36 ch.pipeline().addLast(clientHandler);
41 public EchoClient(final ChannelInitializer<LocalChannel> channelInitializer) {
42 this.channelInitializer = channelInitializer;
47 // Configure the client.
48 EventLoopGroup group = new NioEventLoopGroup();
50 Bootstrap bootstrap = new Bootstrap();
52 bootstrap.group(group)
53 .channel(LocalChannel.class)
54 .handler(channelInitializer);
57 LocalAddress localAddress = new LocalAddress("foo");
58 ChannelFuture future = bootstrap.connect(localAddress).sync();
60 // Wait until the connection is closed.
61 future.channel().closeFuture().sync();
62 } catch (InterruptedException e) {
63 LOG.error("Error in client", e);
64 throw new RuntimeException("Error in client", e);
66 // Shut down the event loop to terminate all threads.
67 LOG.info("Client is shutting down");
68 group.shutdownGracefully();