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
9 package org.opendaylight.controller.netconf.netty;
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;
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
28 public class EchoClient extends Thread {
29 private static final Logger logger = LoggerFactory.getLogger(EchoClient.class);
32 private final ChannelInitializer<LocalChannel> channelInitializer;
35 public EchoClient(final ChannelHandler clientHandler) {
36 channelInitializer = new ChannelInitializer<LocalChannel>() {
38 public void initChannel(LocalChannel ch) throws Exception {
39 ch.pipeline().addLast(clientHandler);
44 public EchoClient(ChannelInitializer<LocalChannel> channelInitializer) {
45 this.channelInitializer = channelInitializer;
50 // Configure the client.
51 EventLoopGroup group = new NioEventLoopGroup();
53 Bootstrap b = new Bootstrap();
56 .channel(LocalChannel.class)
57 .handler(channelInitializer);
60 LocalAddress localAddress = new LocalAddress("foo");
61 ChannelFuture f = b.connect(localAddress).sync();
63 // Wait until the connection is closed.
64 f.channel().closeFuture().sync();
65 } catch (Exception e) {
66 logger.error("Error in client", e);
67 throw new RuntimeException("Error in client", e);
69 // Shut down the event loop to terminate all threads.
70 logger.info("Client is shutting down");
71 group.shutdownGracefully();