@Override
 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
   Channel incoming = ctx.channel();
   for (Channel channel : sChannels) {
     channel.writeAndFlush(
         new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + " 离开"));
   }
   System.out.println("Client:" + incoming.remoteAddress() + "离开");
   sChannels.remove(ctx.channel());
 }
示例#2
0
  public void run(URI uri) throws Exception {
    int port = uri.getPort() > 0 ? uri.getPort() : BaseTestConfig.HTTPS_PORT;
    String host = uri.getHost();

    // Configure SSL context if necessary.
    final SslContext sslCtx;
    sslCtx =
        SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    httpsInitializer = generateHttpsInitializer(sslCtx);
    try {
      Bootstrap b = new Bootstrap();
      b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
      b.group(group).channel(NioSocketChannel.class).handler(httpsInitializer);

      // Make the connection attempt.
      startTime = System.nanoTime();
      Channel ch = b.connect(host, port).sync().channel();
      localAddress = ch.localAddress();
      remoteAddress = ch.remoteAddress();

      sendRequests(uri.toURL(), ch);

      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      endTime = System.nanoTime();
      long duration = endTime - startTime;
      logger.info(String.format("connection duration: %,dns (%d)", duration, duration));
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
 // socket disconnected
 @Override
 public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
   super.channelInactive(ctx);
   final Channel channel = ctx.channel();
   //		this.server.unregister(channel);
   this.log().info("Connection closed: " + channel.remoteAddress().toString());
 }
 public String getRemoteAddress() {
   SocketAddress address = channel.remoteAddress();
   if (address == null) {
     return null;
   }
   return address.toString();
 }
  public synchronized void pause() {
    if (paused) {
      return;
    }

    if (channelClazz == null) {
      return;
    }

    // We *pause* the acceptor so no new connections are made
    if (serverChannelGroup != null) {
      ChannelGroupFuture future = serverChannelGroup.close().awaitUninterruptibly();
      if (!future.isSuccess()) {
        ActiveMQServerLogger.LOGGER.nettyChannelGroupBindError();
        Iterator<Channel> iterator = future.group().iterator();
        while (iterator.hasNext()) {
          Channel channel = iterator.next();
          if (channel.isActive()) {
            ActiveMQServerLogger.LOGGER.nettyChannelStillBound(channel, channel.remoteAddress());
          }
        }
      }
    }
    paused = true;
  }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   Channel incoming = ctx.channel();
   System.out.println("Client:" + incoming.remoteAddress() + "异常");
   cause.printStackTrace();
   ctx.close();
 }
 // 暴力停止客户端,先执行exceptionCaught,接着执行channelInactive。
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
   Channel incoming = ctx.channel();
   System.out.println("SimpleChatClient:" + incoming.remoteAddress() + "异常");
   // 当出现异常就关闭连接
   cause.printStackTrace();
   ctx.close();
 }
示例#8
0
 @Override
 public String toString() {
   return Objects.toStringHelper(this)
       .add("remoteAdress", channel.remoteAddress())
       .add("clientId", clientId)
       .add("isActive", isActive())
       .toString();
 }
 // 暴力停止某个终端,其他终端都会收到离开的信息
 @Override
 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
   Channel incoming = ctx.channel();
   for (Channel channel : channels) {
     channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
   }
   channels.remove(ctx.channel());
 }
 @Override
 public String toString() {
   return super.toString()
       + "[local= "
       + channel.localAddress()
       + ", remote="
       + channel.remoteAddress()
       + "]";
 }
示例#11
0
 @Override
 public void channelActive(ChannelHandlerContext ctx) throws Exception {
   log.debug(
       "channelConnected on OFChannelHandler {}",
       String.format("%08x", System.identityHashCode(this)));
   counters.switchConnected.increment();
   channel = ctx.channel();
   log.info("New switch connection from {}", channel.remoteAddress());
   setState(new WaitHelloState());
 }
示例#12
0
 public ConnectedUser findUserByChan(Channel chan) {
   for (ConnectedUser user : this.connectedUsers) {
     InetSocketAddress argChanAddr = ((InetSocketAddress) chan.remoteAddress());
     InetSocketAddress searchChanAddr = ((InetSocketAddress) user.getChannel().remoteAddress());
     if (searchChanAddr.getAddress().equals(argChanAddr.getAddress())
         && searchChanAddr.getPort() == argChanAddr.getPort()) {
       return user;
     }
   }
   return null;
 }
示例#13
0
  @Override
  public void channelActive(ChannelHandlerContext var1) throws Exception {
    super.channelActive(var1);
    k = var1.channel();
    l = k.remoteAddress();

    try {
      this.a(EnumProtocol.HANDSHAKING);
    } catch (Throwable var3) {
      g.fatal(var3);
    }
  }
示例#14
0
  /**
   * Return a string describing this switch based on the already available information (DPID and/or
   * remote socket)
   *
   * @return
   */
  private String getConnectionInfoString() {

    String channelString;
    if (channel == null || channel.remoteAddress() == null) {
      channelString = "?";
    } else {
      channelString = channel.remoteAddress().toString();
      if (channelString.startsWith("/")) channelString = channelString.substring(1);
    }
    String dpidString;
    if (featuresReply == null) {
      dpidString = "?";
    } else {
      StringBuilder b = new StringBuilder();
      b.append(featuresReply.getDatapathId());
      if (featuresReply.getVersion().compareTo(OFVersion.OF_13) >= 0) {
        b.append("(").append(featuresReply.getAuxiliaryId()).append(")");
      }
      dpidString = b.toString();
    }
    return String.format("[%s from %s]", dpidString, channelString);
  }
 // socket connected
 @Override
 public void channelActive(final ChannelHandlerContext ctx) throws Exception {
   super.channelActive(ctx);
   final Channel channel = ctx.channel();
   // ensure channel matches
   if (!channel.equals(this.dao.channel)) {
     this.log().severe("Channel doesn't match!");
     throw new RuntimeException();
   }
   this.log().info("Accepted connection from: " + channel.remoteAddress().toString());
   //		ctx.write("Welcome!\r\n");
   //		ctx.flush();
   //		this.log().publish("===> ACTIVE");
 }
示例#16
0
 void setChannel(io.netty.channel.Channel channel) {
   this.channel = channel;
   remoteHostAddress = null;
   remotePort = 0;
   if (channel != null) {
     SocketAddress remoteAddr = channel.remoteAddress();
     if (remoteAddr != null) {
       InetSocketAddress addr = (InetSocketAddress) remoteAddr;
       InetAddress ad = addr.getAddress();
       remoteHostAddress = ad.getHostAddress();
       remotePort = addr.getPort();
     }
   }
 }
 public void invokeOnewayImpl(
     final Channel channel, final RemotingCommand request, final long timeoutMillis)
     throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException,
         RemotingSendRequestException {
   request.markOnewayRPC();
   boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
   if (acquired) {
     final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway);
     try {
       channel
           .writeAndFlush(request)
           .addListener(
               new ChannelFutureListener() {
                 @Override
                 public void operationComplete(ChannelFuture f) throws Exception {
                   once.release();
                   if (!f.isSuccess()) {
                     plog.warn(
                         "send a request command to channel <"
                             + channel.remoteAddress()
                             + "> failed.");
                     plog.warn(request.toString());
                   }
                 }
               });
     } catch (Exception e) {
       once.release();
       plog.warn(
           "write send a request command to channel <" + channel.remoteAddress() + "> failed.");
       throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
     }
   } else {
     if (timeoutMillis <= 0) {
       throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast");
     } else {
       String info =
           String.format(
               "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
               timeoutMillis, //
               this.semaphoreAsync.getQueueLength(), //
               this.semaphoreAsync.availablePermits() //
               );
       plog.warn(info);
       plog.warn(request.toString());
       throw new RemotingTimeoutException(info);
     }
   }
 }
  protected void processHeadRequest(
      ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {

    if (_logger.isTraceEnabled()) {
      Channel channel = channelHandlerContext.channel();

      _logger.trace(
          "Client {}: processing head request {}", channel.remoteAddress(), fullHttpRequest.uri());
    }

    SyncFile syncFile = _getSyncFile(fullHttpRequest);

    if (syncFile == null) {
      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    String lanTokenKey = syncFile.getLanTokenKey();

    if ((lanTokenKey == null) || lanTokenKey.isEmpty()) {
      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    String encryptedToken = null;

    try {
      encryptedToken = LanTokenUtil.createEncryptedToken(lanTokenKey);
    } catch (Exception e) {
      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK);

    HttpHeaders httpHeaders = httpResponse.headers();

    httpHeaders.set("connectionsCount", _syncTrafficShapingHandler.getConnectionsCount());

    httpHeaders.set("downloadRate", _trafficCounter.lastWrittenBytes());
    httpHeaders.set("encryptedToken", encryptedToken);
    httpHeaders.set("maxConnections", PropsValues.SYNC_LAN_SERVER_MAX_CONNECTIONS);

    channelHandlerContext.writeAndFlush(httpResponse);
  }
  @Override
  public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable exception) {

    String message = exception.getMessage();

    if (!message.startsWith("An existing connectionn was forcibly closed")
        && !message.startsWith("Connection reset by peer")) {

      Channel channel = channelHandlerContext.channel();

      _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);
    }

    Channel channel = channelHandlerContext.channel();

    channel.close();
  }
示例#20
0
 /**
  * Responds to a single message with some Encodable object. If a failure occurs while sending, it
  * will be logged and the channel closed.
  */
 private void respond(final Encodable result) {
   final String remoteAddress = channel.remoteAddress().toString();
   channel
       .writeAndFlush(result)
       .addListener(
           new ChannelFutureListener() {
             @Override
             public void operationComplete(ChannelFuture future) throws Exception {
               if (future.isSuccess()) {
                 logger.trace(String.format("Sent result %s to client %s", result, remoteAddress));
               } else {
                 logger.error(
                     String.format(
                         "Error sending result %s to %s; closing connection",
                         result, remoteAddress),
                     future.cause());
                 channel.close();
               }
             }
           });
 }
示例#21
0
 @Override
 protected void serviceStart() throws Exception {
   if (bootstrap != null) {
     ChannelFuture channelFuture = bootstrap.connect(config.getHost(), config.getPort()).sync();
     channelFuture.awaitUninterruptibly(config.getConnectTimeout(), TimeUnit.MILLISECONDS);
     if (channelFuture.isSuccess()) {
       channel = channelFuture.channel();
       if (NetUtils.toAddressString((InetSocketAddress) channel.remoteAddress())
           .equals(NetUtils.toAddressString((InetSocketAddress) channel.localAddress()))) {
         channel.close();
         throw new ClientConnectException(
             "Failed to connect "
                 + config.getHost()
                 + ":"
                 + config.getPort()
                 + ". Cause by: Remote and local address are the same");
       }
     } else {
       throw new ClientTimeoutException(channelFuture.cause());
     }
   }
 }
示例#22
0
 public SocketAddress getSocketAddress() {
   return channel.remoteAddress();
 }
  public synchronized void stop() {
    if (channelClazz == null) {
      return;
    }

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

    if (batchFlusherFuture != null) {
      batchFlusherFuture.cancel(false);

      flusher.cancel();

      flusher = null;

      batchFlusherFuture = null;
    }

    // serverChannelGroup has been unbound in pause()
    if (serverChannelGroup != null) {
      serverChannelGroup.close().awaitUninterruptibly();
    }

    if (channelGroup != null) {
      ChannelGroupFuture future = channelGroup.close().awaitUninterruptibly();

      if (!future.isSuccess()) {
        ActiveMQServerLogger.LOGGER.nettyChannelGroupError();
        Iterator<Channel> iterator = future.group().iterator();
        while (iterator.hasNext()) {
          Channel channel = iterator.next();
          if (channel.isActive()) {
            ActiveMQServerLogger.LOGGER.nettyChannelStillOpen(channel, channel.remoteAddress());
          }
        }
      }
    }

    // Shutdown the EventLoopGroup if no new task was added for 100ms or if
    // 3000ms elapsed.
    eventLoopGroup.shutdownGracefully(100, 3000, TimeUnit.MILLISECONDS);
    eventLoopGroup = null;

    channelClazz = null;

    for (Connection connection : connections.values()) {
      listener.connectionDestroyed(connection.getID());
    }

    connections.clear();

    if (notificationService != null) {
      TypedProperties props = new TypedProperties();
      props.putSimpleStringProperty(
          new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName()));
      props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
      props.putIntProperty(new SimpleString("port"), port);
      Notification notification =
          new Notification(null, CoreNotificationType.ACCEPTOR_STOPPED, props);
      try {
        notificationService.sendNotification(notification);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    paused = false;
  }
  protected void processGetRequest(
      ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest)
      throws Exception {

    if (_logger.isTraceEnabled()) {
      Channel channel = channelHandlerContext.channel();

      _logger.trace(
          "Client {}: processing get request {}", channel.remoteAddress(), fullHttpRequest.uri());
    }

    HttpHeaders requestHttpHeaders = fullHttpRequest.headers();

    String lanToken = requestHttpHeaders.get("lanToken");

    if (Validator.isBlank(lanToken)) {
      Channel channel = channelHandlerContext.channel();

      _logger.error("Client {}: did not send token", channel.remoteAddress());

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    if (!LanTokenUtil.containsLanToken(lanToken)) {
      Channel channel = channelHandlerContext.channel();

      _logger.error("Client {}: token not found or expired", channel.remoteAddress());

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    SyncFile syncFile = _getSyncFile(fullHttpRequest);

    if (syncFile == null) {
      if (_logger.isTraceEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.trace(
            "Client {}: SyncFile not found. uri: {}",
            channel.remoteAddress(),
            fullHttpRequest.uri());
      }

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    if (_syncTrafficShapingHandler.getConnectionsCount()
        >= PropsValues.SYNC_LAN_SERVER_MAX_CONNECTIONS) {

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    _syncTrafficShapingHandler.incrementConnectionsCount();

    try {
      sendFile(channelHandlerContext, fullHttpRequest, syncFile);
    } catch (Exception e) {
      _syncTrafficShapingHandler.decrementConnectionsCount();

      throw e;
    }

    LanTokenUtil.removeLanToken(lanToken);
  }
  protected void sendFile(
      final ChannelHandlerContext channelHandlerContext,
      FullHttpRequest fullHttpRequest,
      SyncFile syncFile)
      throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
      _syncTrafficShapingHandler.decrementConnectionsCount();

      if (_logger.isTraceEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
      }

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    if (_logger.isDebugEnabled()) {
      Channel channel = channelHandlerContext.channel();

      _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
      modifiedTime = modifiedTime / 1000 * 1000;
      previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

      _syncTrafficShapingHandler.decrementConnectionsCount();

      Channel channel = channelHandlerContext.channel();

      _logger.error(
          "Client {}: file modified {}, currentTime {}, modifiedTime "
              + "{}, previousModifiedTime {}",
          channel.remoteAddress(),
          path,
          currentTime,
          modifiedTime,
          previousModifiedTime);

      _sendError(channelHandlerContext, NOT_FOUND);

      return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(
        HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
      httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture =
        channelHandlerContext.writeAndFlush(
            new HttpChunkedInput(syncChunkedFile), channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(
        new ChannelFutureListener() {

          @Override
          public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
              return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error(
                "Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
          }
        });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
      channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
  }
示例#26
0
 @Override
 public String getIp() {
   return channel.remoteAddress().toString();
 }
 // 暴力停止客户端,先执行exceptionCaught,接着执行channelInactive。
 @Override
 public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
   Channel incoming = ctx.channel();
   System.out.println("SimpleChatClient:" + incoming.remoteAddress() + "掉线");
 }
示例#28
0
文件: Session.java 项目: Munien/luna
 /**
  * Creates a new {@link Session}.
  *
  * @param channel The {@link Channel} to send and receive messages through.
  */
 public Session(Channel channel) {
   this.channel = channel;
   this.hostAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
 }