當前位置: 首頁>>代碼示例>>Java>>正文


Java Channel.close方法代碼示例

本文整理匯總了Java中io.netty.channel.Channel.close方法的典型用法代碼示例。如果您正苦於以下問題:Java Channel.close方法的具體用法?Java Channel.close怎麽用?Java Channel.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在io.netty.channel.Channel的用法示例。


在下文中一共展示了Channel.close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: closeChannelGracefully

import io.netty.channel.Channel; //導入方法依賴的package包/類
static void closeChannelGracefully(InetSocketAddress udpSource) {
    Channel socksChannel = removeSocksMapping(udpSource);
    Channel udpChannel = removeUdpMapping(udpSource);
    Channel tcpChannel = removeTcpMapping(udpSource);
    if (tcpChannel.isActive()) {
        tcpChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        log.info("\t          Proxy << Target \tDisconnect");
    }
    if (socksChannel.isActive()) {
        socksChannel.close();
        log.info("\tClient << Proxy           \tDisconnect");
    }
    if (udpChannel.isActive()) {
        udpChannel.close();
    }
}
 
開發者ID:ZhangJiupeng,項目名稱:AgentX,代碼行數:17,代碼來源:XChannelMapper.java

示例2: removeChannel

import io.netty.channel.Channel; //導入方法依賴的package包/類
/**
 * 從緩存中移除Channel,並且關閉Channel
 * @param channel
 */
public void removeChannel(Channel channel){
    try{
        logger.warn("channel will be remove, address is :{}", NettyUtil.parseChannelRemoteAddr(channel));
        rwLock.writeLock().lock();
        channel.close();
        ChatUser chatUser= chatUserMap.get(channel);
        if (chatUser!=null){
            ChatUser tmp = chatUserMap.remove(channel);
            if (tmp != null && tmp.isAuth()) {
                // 減去一個認證用戶
                userCount.decrementAndGet();
            }
        }

    }finally {
        rwLock.writeLock().unlock();
    }
}
 
開發者ID:ChinaLHR,項目名稱:JavaQuarkBBS,代碼行數:23,代碼來源:ChannelManager.java

示例3: registerServerSession

import io.netty.channel.Channel; //導入方法依賴的package包/類
/**
 * 注冊RPC生產者Session
 * 
 * @param ctx
 * @param providerName
 * @param rpcServerPort
 * @param rpcServerIp
 * @return
 */
private ServiceXServerSession registerServerSession(Channel channel, String rpcServerIp, int rpcServerPort,
		int providerId) {
	if (rpcServers.containsKey(providerId)) {
		channel.close();
		log.error("服務提供者ID重複,斷開鏈接,IP:" + channel.remoteAddress() + ",服務者ID:" + providerId);
		return null;
	}
	ServiceXServerSession session = new ServiceXServerSession();
	session.setSession(channel);
	session.setProviderId(providerId);
	session.setServerIp(rpcServerIp);
	session.setServerPort(rpcServerPort);
	rpcServers.put(session.getProviderId(), session);
	log.info("RPC生產者[" + providerId + "]注冊到服務中心:" + channel.remoteAddress() + ",生產者中心大小:" + rpcServers.size());
	return session;
}
 
開發者ID:HankXV,項目名稱:Limitart,代碼行數:26,代碼來源:ServiceCenterX.java

示例4: removeChannel

import io.netty.channel.Channel; //導入方法依賴的package包/類
/**
 * 從緩存中移除Channel,並且關閉Channel
 *
 * @param channel
 */
public static void removeChannel(Channel channel) {
    try {
        logger.warn("channel will be remove, address is :{}", NettyUtil.parseChannelRemoteAddr(channel));
        rwLock.writeLock().lock();
        channel.close();
        UserInfo userInfo = userInfos.get(channel);
        if (userInfo != null) {
            UserInfo tmp = userInfos.remove(channel);
            if (tmp != null && tmp.isAuth()) {
                // 減去一個認證用戶
                userCount.decrementAndGet();
            }
        }
    } finally {
        rwLock.writeLock().unlock();
    }

}
 
開發者ID:beyondfengyu,項目名稱:HappyChat,代碼行數:24,代碼來源:UserInfoManager.java

示例5: preCreateConnections

import io.netty.channel.Channel; //導入方法依賴的package包/類
@Override
public void preCreateConnections(final int count)
throws ConnectException, IllegalArgumentException {
	if(count > 0) {
		for(int i = 0; i < count; i ++) {
			final Channel conn = connectToAnyNode();
			if(conn == null) {
				throw new ConnectException(
					"Failed to pre-create the connections to the target nodes"
				);
			}
			final String nodeAddr = conn.attr(ATTR_KEY_NODE).get();
			if(conn.isActive()) {
				final Queue<Channel> connQueue = availableConns.get(nodeAddr);
				if(connQueue != null) {
					connQueue.add(conn);
				}
			} else {
				conn.close();
			}
		}
		LOG.info("Pre-created " + count + " connections");
	} else {
		throw new IllegalArgumentException("Connection count should be > 0, but got " + count);
	}
}
 
開發者ID:akurilov,項目名稱:netty-connection-pool,代碼行數:27,代碼來源:BasicMultiNodeConnPool.java

示例6: notifyDied

import io.netty.channel.Channel; //導入方法依賴的package包/類
public void notifyDied(String username, EntityDamageEvent.DamageCause cause) {
    webSocketServerThread.log(Level.INFO, "web user "+username+"'s entity died from "+cause);

    Channel channel = name2channel.get(username);
    if (channel != null) {
        String message = "T,You died from "+(cause == null ? "unknown causes" : cause);

        if (!dieDisconnect) {
            message += ", but remain connected to the server as a ghost";
        }

        webSocketServerThread.sendLine(channel, message);

        if (dieDisconnect) {
            channel.close();
            clientDisconnected(channel);
        }
    }
}
 
開發者ID:satoshinm,項目名稱:WebSandboxMC,代碼行數:20,代碼來源:WebPlayerBridge.java

示例7: handleNewClient

import io.netty.channel.Channel; //導入方法依賴的package包/類
public void handleNewClient(ChannelHandlerContext ctx, String username, String token) {
        Channel channel = ctx.channel();

        if (!webPlayerBridge.newPlayer(channel, username, token)) {
            channel.close();
            return;
        }

        allUsersGroup.add(channel);


    /* Send initial server messages on client connect here, example from Python server for comparison:

U,1,0,0,0,0,0
E,1491627331.01,600
T,Welcome to Craft!
T,Type "/help" for a list of commands.
N,1,guest1
*/
        sendLine(channel, "B,0,0,0,30,0,1"); // floating grass block at (0,30,0) in chunk (0,0)
        sendLine(channel, "K,0,0,0"); // update chunk key (0,0) to 0
        sendLine(channel, "R,0,0"); // refresh chunk (0,0)

        blockBridge.sendWorld(channel);
        playersBridge.sendPlayers(channel);
    }
 
開發者ID:satoshinm,項目名稱:WebSandboxMC,代碼行數:27,代碼來源:WebSocketServerThread.java

示例8: handshake

import io.netty.channel.Channel; //導入方法依賴的package包/類
protected void handshake(HelloMessage request, Channel channel) {
    try {
        switch (getAuthScheme()) {
            case CHALLENGE_RESPONSE:
                handshakeChallengeResponse(request, channel);
                break;
            case NO_AUTH:
                // shouldn't get here
                break;
        }
    } catch (AuthException e) {
        logger.warn("[{}->{}] Failed to authenticate connection: {}",
                    new Object[]{getLocalNodeIdString(), 
                                 getRemoteNodeIdString(), 
                                 e.getMessage()});
        channel.writeAndFlush(getError(request.getHeader().getTransactionId(), 
                               e, MessageType.HELLO));
        channel.close();
    }
}
 
開發者ID:xuraylei,項目名稱:fresco_floodlight,代碼行數:21,代碼來源:AbstractRPCChannelHandler.java

示例9: startDownTask

import io.netty.channel.Channel; //導入方法依賴的package包/類
public static void startDownTask(TaskInfo taskInfo, HttpRequest httpRequest,
    HttpResponse httpResponse, Channel clientChannel) {
  HttpHeaders httpHeaders = httpResponse.headers();
  HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest);
  HttpDownServer.DOWN_CONTENT.put(taskInfo.getId(), httpDownInfo);
  httpHeaders.clear();
  httpResponse.setStatus(HttpResponseStatus.OK);
  httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/html");
  String host = HttpDownServer.isDev() ? "localhost"
      : ((InetSocketAddress) clientChannel.localAddress()).getHostString();
  String js =
      "<script>window.top.location.href='http://" + host + ":" + HttpDownServer.VIEW_SERVER_PORT
          + "/#/tasks/new/" + httpDownInfo
          .getTaskInfo().getId()
          + "';</script>";
  HttpContent content = new DefaultLastHttpContent();
  content.content().writeBytes(js.getBytes());
  httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, js.getBytes().length);
  clientChannel.writeAndFlush(httpResponse);
  clientChannel.writeAndFlush(content);
  clientChannel.close();
}
 
開發者ID:monkeyWie,項目名稱:proxyee-down,代碼行數:23,代碼來源:HttpDownUtil.java

示例10: channelRead0

import io.netty.channel.Channel; //導入方法依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, Packet packet) throws Exception {
	Channel channel = ctx.channel();
	Server server = Cloud.getInstance().getServerManager().getChannelToServer().get(channel);

	if (packet instanceof PacketPing && server != null) {
		PacketPing pingPacket = (PacketPing) packet;
		long ping = System.currentTimeMillis() - pingPacket.getTimestamp();
		server.setPing(ping);
	} else if (packet instanceof PacketServerRegister) {
		PacketServerRegister registerPacket = (PacketServerRegister) packet;
		switch (registerPacket.getType()) {
			case BUNGEECORD:
				BungeeServer bungeeServer = new BungeeServer(channel);
				bungeeServer.setPrefix("bungee");
				Cloud.getInstance().getServerManager().registerServer(bungeeServer);
				break;
			case SPIGOT:
				SpigotServer spigotServer = new SpigotServer(channel);
				spigotServer.setPrefix(registerPacket.getPrefix());
				spigotServer.setBukkitPort(registerPacket.getBukkitPort());
				Cloud.getInstance().getServerManager().registerServer(spigotServer);
				break;
			case DAEMON:
				Daemon daemon = new Daemon(channel);
				daemon.setPrefix("daemon");
				Cloud.getInstance().getServerManager().registerServer(daemon);
				break;
			default:
		}
	} else if (packet instanceof PacketCloseConnection) {
		channel.close();
	} else if (packet instanceof PacketServerLoad) {
		PacketServerLoad serverLoad = (PacketServerLoad) packet;
		Cloud.getInstance().getEventManager().callEvent(new DaemonLoadEvent(serverLoad.getCpuLoad(), serverLoad.getFreeRam(), server));
	}

	Cloud.getInstance().getEventManager().callEvent(new PacketReceivingEvent(packet, server));

}
 
開發者ID:CentauriCloud,項目名稱:CentauriCloud,代碼行數:41,代碼來源:NetworkHandler.java

示例11: closeChannelGracefully

import io.netty.channel.Channel; //導入方法依賴的package包/類
static void closeChannelGracefully(InetSocketAddress udpSource) {
    Channel udpChannel = removeUdpMapping(udpSource);
    Channel tcpChannel = removeTcpMapping(udpSource);
    if (udpChannel.isActive()) {
        log.info("\t          Proxy << Target \tDisconnect");
        udpChannel.close();
    }
    if (tcpChannel.isActive()) {
        tcpChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        log.info("\tClient << Proxy           \tDisconnect");
    }
}
 
開發者ID:ZhangJiupeng,項目名稱:AgentX,代碼行數:13,代碼來源:XChannelMapper.java

示例12: clearUnheart

import io.netty.channel.Channel; //導入方法依賴的package包/類
private void clearUnheart() {
	if (checkHeartWhenConnectionCount > connectionCount.get()) {
		return;
	}
	long now = System.currentTimeMillis();
	for (Channel channel : validatedChannels) {
		long last = 0;
		long first = 0;
		int count = 0;
		if (channel.hasAttr(LAST_HEART_TIME)) {
			last = channel.attr(LAST_HEART_TIME).get();
		}
		if (channel.hasAttr(FIRST_HEART_TIME)) {
			first = channel.attr(FIRST_HEART_TIME).get();
		}
		if (channel.hasAttr(HEART_COUNT)) {
			count = channel.attr(HEART_COUNT).get();
		}
		int allow = (int) ((now - first) / (heartIntervalSec * 1000));
		if (count - 2 > allow) {
			log.error(channel + " heart too quick,might be Game Accelerator,please check!");
			channel.pipeline().fireExceptionCaught(new HeartTooQuickException(channel, first, now, count, allow));
			channel.attr(FIRST_HEART_TIME).set(now);
			channel.attr(HEART_COUNT).set(0);
		}
		if (count < allow - 2) {
			channel.pipeline().fireExceptionCaught(new HeartNotAnswerException(channel, first, last, count));
			channel.close();
		}
	}
}
 
開發者ID:HankXV,項目名稱:Limitart,代碼行數:32,代碼來源:BinaryServer.java

示例13: channelRead0

import io.netty.channel.Channel; //導入方法依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
        throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }
    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException(
                "Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
                    ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    } else if (msg instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) msg;
        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            System.out.println("WebSocket Client received message: " + textFrame.text());
        } else if (msg instanceof PongWebSocketFrame) {
            System.out.println("WebSocket Client received pong");
        } else if (msg instanceof CloseWebSocketFrame) {
            System.out.println("WebSocket Client received closing");
            ch.close();
        }
    }
}
 
開發者ID:AlexMog,項目名稱:SurvivalMMO,代碼行數:29,代碼來源:WebSocketClientHandler.java

示例14: destroy

import io.netty.channel.Channel; //導入方法依賴的package包/類
public void destroy() {
  logger.info("MQTT server is stopping...");
  for (Channel channel : channels) {
    channel.close();
  }
  bossGroup.shutdownGracefully();
  workerGroup.shutdownGracefully();
  logger.info("MQTT server is stopped...");
}
 
開發者ID:osswangxining,項目名稱:mqttserver,代碼行數:10,代碼來源:Server.java

示例15: release

import io.netty.channel.Channel; //導入方法依賴的package包/類
@Override
public final void release(final Channel conn) {
	final String nodeAddr = conn.attr(ATTR_KEY_NODE).get();
	if(conn.isActive()) {
		final Queue<Channel> connQueue = availableConns.get(nodeAddr);
		if(connQueue != null) {
			connQueue.add(conn);
		}
		concurrencyThrottle.release();
	} else {
		conn.close();
	}
}
 
開發者ID:akurilov,項目名稱:netty-connection-pool,代碼行數:14,代碼來源:BasicMultiNodeConnPool.java


注:本文中的io.netty.channel.Channel.close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。