@Override
  public boolean process(SmppSimulatorSessionHandler session, Channel channel, Pdu pdu)
      throws Exception {
    // anything other than a bind is super bad!
    if (!(pdu instanceof BaseBind)) {
      if (pdu instanceof PduRequest) {
        session.addPduToWriteOnNextPduReceived(
            ((PduRequest) pdu).createGenericNack(SmppConstants.STATUS_INVBNDSTS));
        return true;
      } else {
        // logger.error("PDU response received, but not bound");
        channel.close();
        return true;
      }
    }

    BaseBind bind = (BaseBind) pdu;
    BaseBindResp bindResp = (BaseBindResp) bind.createResponse();

    if (!bind.getSystemId().equals(systemId)) {
      bindResp.setCommandStatus(SmppConstants.STATUS_INVSYSID);
    } else if (!bind.getPassword().equals(password)) {
      bindResp.setCommandStatus(SmppConstants.STATUS_INVPASWD);
    }

    session.addPduToWriteOnNextPduReceived(bindResp);
    return true;
  }
Ejemplo n.º 2
0
  /**
   * Logs out of the current IMAP session and releases all resources, including executor services.
   */
  @Override
  public synchronized void disconnect() {
    try {
      // If there is an error with the handler, dont bother logging out.
      if (!mailClientHandler.isHalted()) {
        if (mailClientHandler.idleRequested.get()) {
          log.warn("Disconnect called while IDLE, leaving idle and logging out.");
          done();
        }

        // Log out of the IMAP Server.
        channel.write(". logout\n");
      }

      currentFolder = null;
    } catch (Exception e) {
      // swallow any exceptions.
    } finally {
      // Shut down all channels and exit (leave threadpools as is--for reconnects).
      // The Netty channel close listener will fire a disconnect event to our client,
      // automatically. See connect() for details.
      try {
        channel.close().awaitUninterruptibly(config.getTimeout(), TimeUnit.MILLISECONDS);
      } catch (Exception e) {
        // swallow any exceptions.
      } finally {
        mailClientHandler.idleAcknowledged.set(false);
        mailClientHandler.disconnected();
        if (disconnectListener != null) disconnectListener.disconnected();
      }
    }
  }
 protected void nuke() {
   state = NodeConnectionState.NONE;
   if (pendingFuture != null) pendingFuture.cancel();
   if (nodeChannel != null) nodeChannel.close();
   pendingFuture = null;
   nodeChannel = null;
 }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   e.getCause().printStackTrace();
   Channel channel = e.getChannel();
   channel.close();
   System.out.println("exceptionCaught...");
 }
Ejemplo n.º 5
0
 private void httpRequestReceived(HttpRequest request, Channel channel) {
   HttpResponse response = getResponse(request);
   eventBus.post(response);
   channel.write(response);
   channel.disconnect();
   channel.close();
 }
  protected void sendRequest(
      HttpRequest request,
      SendRequestResultListener listener,
      HttpResponseProcessor responseProcessor) {
    if (isClosingOrClosed()) {
      listener.onSendRequestFailure(request, new ClosedChannelException());
    } else if (!isConnected()) {
      listener.onSendRequestFailure(request, new RuntimeException("unable to send request"));
    } else {
      try {
        setResponseProcessor(responseProcessor, listener);
      } catch (DatabusException e) {
        listener.onSendRequestFailure(request, e.getCause());
        _channel.close();
        return;
      }

      // Send the HTTP request.
      if (_channel.isConnected()) {
        // ChannelFuture future = _channel.write(request);
        // future.addListener(new MySendRequestListener(request, listener));
        _channel.write(request);
      } else {
        _log.error("disconnect on request: " + request.getUri());
        listener.onSendRequestFailure(request, new ClosedChannelException());
      }
    }
  }
 public static void remoteCapiClose(Channel channel) {
   try {
     channel.close().await(DISCONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
     // ignore
   }
 }
Ejemplo n.º 8
0
 /** Close the connection. */
 public synchronized void close() {
   if (!closed && channel != null) {
     ConnectionWatchdog watchdog = channel.getPipeline().get(ConnectionWatchdog.class);
     watchdog.setReconnect(false);
     closed = true;
     channel.close();
   }
 }
Ejemplo n.º 9
0
 /**
  * Closes the given channel
  *
  * @param channel the channel to close
  */
 public static void close(Channel channel) {
   if (channel != null) {
     if (LOG.isTraceEnabled()) {
       LOG.trace("Closing channel: " + channel);
     }
     channel.close().awaitUninterruptibly();
   }
 }
Ejemplo n.º 10
0
  private void closeChannel() {
    try {
      channel.close();
    } catch (Exception e) {

    }
    channel = null;
  }
Ejemplo n.º 11
0
 @Test
 public void testTimeToSendMessages() throws Exception {
   connectSender();
   senderThread.join();
   reportLatencies();
   listenerChannel.close();
   listenerChannel.unbind();
   bootstrap.releaseExternalResources();
 }
 private void close(Channel channel) {
   try {
     channel
         .getPipeline()
         .getContext(NettyAsyncHttpProvider.class)
         .setAttachment(new NettyAsyncHttpProvider.DiscardEvent());
     channel.close();
   } catch (Throwable t) {
     // noop
   }
 }
Ejemplo n.º 13
0
 /**
  * Closes the given channel asynchronously
  *
  * @param channel the channel to close
  */
 public static void close(Channel channel) {
   if (channel != null) {
     channel
         .close()
         .addListener(
             new ChannelFutureListener() {
               public void operationComplete(ChannelFuture future) {
                 LOG.trace("Channel closed: {}", future.getChannel());
               }
             });
   }
 }
Ejemplo n.º 14
0
  @Override
  public void releaseResource() {

    try {
      serverChannel.close().awaitUninterruptibly();
      bootstrap.getFactory().releaseExternalResources();
      bootstrap.releaseExternalResources();
    } catch (Exception ex) {
      logger.error(ex, ex);
    }

    logger.info("SocketMasterConnector releaseResource now.");
  }
Ejemplo n.º 15
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   // avoid stack overflow when exception happens on close
   if (TRUE != ctx.getAttachment()) {
     ctx.setAttachment(TRUE);
     // close channel and avoid warning logged by default exceptionCaught implementation
     Channel channel = ctx.getChannel();
     channel.close();
   } else {
     // log exception during close
     super.exceptionCaught(ctx, e);
   }
 }
Ejemplo n.º 16
0
  public void close() {

    ChannelFuture close = channel.close().awaitUninterruptibly();
    close.addListener(
        new ChannelFutureListener() {

          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            System.out.println("Closed.");
          }
        });
    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
  }
  /** Closes the connection. Note: this method will block until the connection is actually closed */
  @Override
  public void close() {
    _log.info("closing connection to: " + _server.getAddress());
    final State newState = switchToClosing();
    if (State.CLOSING != newState && State.CLOSED != newState) {
      return;
    }

    if (null == _channel || !_channel.isConnected()) {
      switchToClosed();
    } else {
      _channel.close();
      awaitForCloseUninterruptibly();
    }
  }
Ejemplo n.º 18
0
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    if (httpChildChannel != null) {
      HttpChildChannel httpChildChannel = this.httpChildChannel;
      this.httpChildChannel = null;

      if (httpChildChannel.setReadClosed() || httpChildChannel.setWriteClosed()) {
        fireExceptionCaught(httpChildChannel, e.getCause());
        fireChannelClosed(httpChildChannel);
      }
    }

    Channel channel = ctx.getChannel();
    channel.close();
  }
Ejemplo n.º 19
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   final Channel channel = ctx.getChannel();
   Message m = (Message) e.getMessage();
   Tuple t = cb.receive(m);
   if (m.type() == Type.DEREG) {
     channel.close();
   }
   if (t != null) {
     if (m.type() == Type.REG) {
       PhysicalLocation pl = new PhysicalLocation(m.source().logId(), (Integer) t.get(0));
       plMap.put(pl, channel);
       ctx.setAttachment(pl);
     }
     Message rsp = new Message(m.type(), m.getAck(), m.destination(), m.source(), t);
     channel.write(rsp);
   }
 }
Ejemplo n.º 20
0
  @Override
  public synchronized NettyWebServer stop() throws IOException {
    if (channel != null) {
      channel.close();
    }
    if (connectionTrackingHandler != null) {
      connectionTrackingHandler.closeAllConnections();
      connectionTrackingHandler = null;
    }
    if (bootstrap != null) {
      bootstrap.releaseExternalResources();
    }
    for (ExecutorService executorService : executorServices) {
      executorService.shutdown();
    }

    bootstrap = null;

    return this;
  }
  @Override
  protected void doStop() {
    synchronized (serverChannels) {
      if (serverChannels != null) {
        for (Channel channel : serverChannels) {
          channel.close().awaitUninterruptibly();
        }
        serverChannels = null;
      }
    }

    if (serverOpenChannels != null) {
      serverOpenChannels.close();
      serverOpenChannels = null;
    }

    if (serverBootstrap != null) {
      serverBootstrap.releaseExternalResources();
      serverBootstrap = null;
    }
  }
Ejemplo n.º 22
0
    /** The server has received a message. */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
      PaxosMessage msg;

      // Get our consensus message and hand it back to the parent.
      msg = (PaxosMessage) e.getMessage();
      if (msg != null) {
        // Try to get remote connection information.
        // This is used if we need to update the network
        // information later.
        Channel channel = ctx.getChannel();
        InetSocketAddress remote = (InetSocketAddress) channel.getRemoteAddress();

        // Update the message with the remote address.
        msg.setRemoteAddress(remote.getAddress().getHostAddress());

        // Update the client.
        updateCallback(msg);

        // Close the channel so that we don't leak descriptors.
        channel.close();
      }
    }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Channel ch = ctx.getChannel();
    if (!handshaker.isHandshakeComplete()) {
      handshaker.finishHandshake(ch, (HttpResponse) e.getMessage());

      handler.onConnect();

      return;
    }

    if (e.getMessage() instanceof HttpResponse) {
      HttpResponse response = (HttpResponse) e.getMessage();
      String message =
          "Unexpected HttpResponse (status="
              + response.getStatus()
              + ", content="
              + response.getContent().toString(CharsetUtil.UTF_8)
              + ')';
      log.error(String.format("Web socket client: %s", message));

      throw new Exception(message);
    }

    WebSocketFrame frame = (WebSocketFrame) e.getMessage();
    if (frame instanceof TextWebSocketFrame) {
      TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
      try {
        handler.onReceive(MAPPER.parseObject(textFrame.getText()));
      } catch (Exception e1) {
        log.error("Error while decoding JSON websocket message", e1);
      }
    } else if (frame instanceof PongWebSocketFrame) {
    } else if (frame instanceof CloseWebSocketFrame) {
      ch.close();
    }
  }
Ejemplo n.º 24
0
 public synchronized void connect() {
   if (this.connected) {
     return;
   }
   logger.info("client is connecting to " + this.host + ":" + this.port);
   ChannelFuture future = null;
   try {
     future = bootstrap.connect(new InetSocketAddress(host, port));
     if (future.awaitUninterruptibly(connectTimeout, TimeUnit.MILLISECONDS)) {
       if (future.isSuccess()) {
         Channel newChannel = future.getChannel();
         try {
           // 关闭旧的连接
           Channel oldChannel = this.channel;
           if (oldChannel != null) {
             logger.info("close old netty channel " + oldChannel);
             try {
               oldChannel.close();
             } catch (Throwable t) {
             }
           }
         } finally {
           this.channel = newChannel;
         }
         logger.info("client is connected to " + this.host + ":" + this.port);
         this.connected = true;
       } else {
         logger.info("client is not connected to " + this.host + ":" + this.port);
       }
     } else {
       logger.info("timeout while connecting to " + this.host + ":" + this.port);
     }
   } catch (Throwable e) {
     logger.info("error while connecting to " + this.host + ":" + this.port, e);
   }
 }
  @Test
  @SuppressWarnings("deprecation")
  public void testCompatibleObjectEcho() throws Throwable {
    ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor));
    ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor));

    EchoHandler sh = new EchoHandler();
    EchoHandler ch = new EchoHandler();

    sb.getPipeline().addLast("decoder", new CompatibleObjectDecoder());
    sb.getPipeline().addLast("encoder", new CompatibleObjectEncoder());
    sb.getPipeline().addLast("handler", sh);

    cb.getPipeline().addLast("decoder", new CompatibleObjectDecoder());
    cb.getPipeline().addLast("encoder", new CompatibleObjectEncoder());
    cb.getPipeline().addLast("handler", ch);

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());

    Channel cc = ccf.getChannel();
    for (String element : data) {
      cc.write(element);
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }
Ejemplo n.º 26
0
 /** Close the connection */
 public void close() {
   channel.close();
 }
Ejemplo n.º 27
0
 public ChannelFuture close() {
   return channel.close();
 }
Ejemplo n.º 28
0
 public void disconnect() {
   channel.write(new DisconnectMessage()).awaitUninterruptibly();
   channel.close().awaitUninterruptibly();
   bootstrap.releaseExternalResources();
 }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
   e.getCause().printStackTrace();
   Channel ch = e.getChannel();
   ch.close();
 }
Ejemplo n.º 30
0
  public static void main(String[] args) {
    final int payloadSize = 100;
    int CYCLE_SIZE = 50000;
    final long NUMBER_OF_ITERATIONS = 500000;

    ChannelBuffer message = ChannelBuffers.buffer(100);
    for (int i = 0; i < message.capacity(); i++) {
      message.writeByte((byte) i);
    }

    // Configure the server.
    ServerBootstrap serverBootstrap =
        new ServerBootstrap(
            new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // Set up the pipeline factory.
    serverBootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          @Override
          public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new EchoServerHandler());
          }
        });

    // Bind and start to accept incoming connections.
    serverBootstrap.bind(new InetSocketAddress(9000));

    ClientBootstrap clientBootstrap =
        new ClientBootstrap(
            new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    //        ClientBootstrap clientBootstrap = new ClientBootstrap(
    //                new OioClientSocketChannelFactory(Executors.newCachedThreadPool()));

    // Set up the pipeline factory.
    final EchoClientHandler clientHandler = new EchoClientHandler();
    clientBootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          @Override
          public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(clientHandler);
          }
        });

    // Start the connection attempt.
    ChannelFuture future = clientBootstrap.connect(new InetSocketAddress("localhost", 9000));
    future.awaitUninterruptibly();
    Channel clientChannel = future.getChannel();

    System.out.println("Warming up...");
    for (long i = 0; i < 10000; i++) {
      clientHandler.latch = new CountDownLatch(1);
      clientChannel.write(message);
      try {
        clientHandler.latch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Warmed up");

    long start = System.currentTimeMillis();
    long cycleStart = System.currentTimeMillis();
    for (long i = 1; i < NUMBER_OF_ITERATIONS; i++) {
      clientHandler.latch = new CountDownLatch(1);
      clientChannel.write(message);
      try {
        clientHandler.latch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      if ((i % CYCLE_SIZE) == 0) {
        long cycleEnd = System.currentTimeMillis();
        System.out.println(
            "Ran 50000, TPS " + (CYCLE_SIZE / ((double) (cycleEnd - cycleStart) / 1000)));
        cycleStart = cycleEnd;
      }
    }
    long end = System.currentTimeMillis();
    long seconds = (end - start) / 1000;
    System.out.println(
        "Ran ["
            + NUMBER_OF_ITERATIONS
            + "] iterations, payload ["
            + payloadSize
            + "]: took ["
            + seconds
            + "], TPS: "
            + ((double) NUMBER_OF_ITERATIONS) / seconds);

    clientChannel.close().awaitUninterruptibly();
    clientBootstrap.releaseExternalResources();
    serverBootstrap.releaseExternalResources();
  }