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.netconf.netty;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.nio.charset.StandardCharsets.UTF_8;
14 import io.netty.buffer.ByteBuf;
15 import io.netty.buffer.Unpooled;
16 import io.netty.channel.ChannelFuture;
17 import io.netty.channel.ChannelFutureListener;
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.ChannelInboundHandlerAdapter;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * Handler implementation for the echo client. It initiates the ping-pong
25 * traffic between the echo client and server by sending the first message to
28 public class EchoClientHandler extends ChannelInboundHandlerAdapter implements ChannelFutureListener {
29 private static final Logger LOG = LoggerFactory.getLogger(EchoClientHandler.class);
31 private ChannelHandlerContext context;
32 private final StringBuilder fromServer = new StringBuilder();
35 CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED
39 private State state = State.CONNECTING;
42 public synchronized void channelActive(ChannelHandlerContext ctx) {
43 checkState(context == null);
44 LOG.info("channelActive");
46 state = State.CONNECTED;
50 public synchronized void channelInactive(ChannelHandlerContext ctx) throws Exception {
51 state = State.CONNECTION_CLOSED;
55 public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
56 ByteBuf bb = (ByteBuf) msg;
57 String string = bb.toString(UTF_8);
58 fromServer.append(string);
59 LOG.info(">{}", string);
64 public synchronized void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
65 // Close the connection when an exception is raised.
66 LOG.warn("Unexpected exception from downstream.", cause);
67 checkState(context.equals(ctx));
72 public synchronized void write(String message) {
73 ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes());
74 context.writeAndFlush(byteBuf);
77 public synchronized boolean isConnected() {
78 return state == State.CONNECTED;
81 public synchronized String read() {
82 return fromServer.toString();
86 public synchronized void operationComplete(ChannelFuture future) throws Exception {
87 checkState(state == State.CONNECTING);
88 if (future.isSuccess()) {
89 LOG.trace("Successfully connected, state will be switched in channelActive");
91 state = State.FAILED_TO_CONNECT;
95 public State getState() {