Java Code Examples for io.netty.channel.Channel#isOpen()
The following examples show how to use
io.netty.channel.Channel#isOpen() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HijUtils.java From PlayerSQL with GNU General Public License v2.0 | 6 votes |
/** * Prevents automatic reading of a player's packets, * and replaces channels to prevent any other ops resetting automatic reading. * * @param player the player * @param autoRead the states of automatic reading */ public void setAutoRead(Player player, boolean autoRead) throws Exception { Channel ch = scripting.getChannel(player); if (ch.isOpen()) { if (autoRead) { if (ch instanceof ChannelProxies.IWrappedChannel) { ch = ((ChannelProxies.IWrappedChannel) ch).channel(); scripting.setChannel(player, ch); } ch.config().setAutoRead(true); } else { ch.config().setAutoRead(false); scripting.setChannel(player, ChannelProxies.create(ch, new HijConfig(ch.config()))); } } }
Example 2
Source File: GetJobsAction.java From spinach with Apache License 2.0 | 6 votes |
/** * Disconnect the channel. Why {@link Channel#disconnect()} and not {@link DisqueCommands#quit()}? The quit command produces * an {@code OK} result which is read by the channel. Sometimes the pipeline is not finished with reading but the disconnect * is already initiated and this raises an {@link java.io.IOException}. * * The {@link Channel} is retrieved by reflection because it is not exposed. * * @param redisChannelHandler the channel handler. */ private void disconnect(RedisChannelHandler<?, ?> redisChannelHandler) { RedisChannelHandler<?, ?> rch = redisChannelHandler; RedisChannelWriter<?, ?> channelWriter = rch.getChannelWriter(); try { Field field = CommandHandler.class.getDeclaredField("channel"); field.setAccessible(true); Channel o = (Channel) field.get(channelWriter); if (o != null && o.isOpen()) { o.disconnect(); } } catch (Exception e) { throw new IllegalStateException("Cannot look up/retrieve the channel from the " + CommandHandler.class.getName()); } }
Example 3
Source File: RemoterHA.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * Write to channel. * * @param channel the channel * @param magicBytes the magic bytes * @param pathOrCommand the path or command * @param attachment the attachment */ private void writeToChannel(Channel channel, String[] magicBytes, Object pathOrCommand, Object attachment) throws ConnectException { long firstAttempt = System.currentTimeMillis(); long timeOut = RemotingConstants.TEN * RemotingConstants.THOUSAND; while (!channel.isOpen() || !channel.isActive()) { if (System.currentTimeMillis() - firstAttempt >= timeOut) { try { throw new TimeoutException(); } catch (TimeoutException e) { logger.error("Waited for 10 sec for connection reattempt to JumbuneAgent, but failed to connect", e); } break; } } if (!channel.isActive()) { logger.warn("channel #" + channel.hashCode() + " still disconnected, about to write on disconnected Channel"); } if (attachment != null && attachment instanceof CyclicBarrier) { channel.attr(RemotingConstants.barrierKey).set((CyclicBarrier)attachment); }else if (attachment != null) { channel.attr(RemotingConstants.handlerKey).set((ChannelInboundHandler)attachment); } channel.write(Unpooled.wrappedBuffer(magicBytes[0].getBytes(), magicBytes[1].getBytes(), magicBytes[2].getBytes())); channel.write(pathOrCommand); channel.flush(); }
Example 4
Source File: P2PClient.java From thunder with GNU Affero General Public License v3.0 | 6 votes |
private void connect (ClientObject node, ConnectionListener connectionListener) { boolean successfulConnection = false; try { System.out.println("Connect to " + node.host + ":" + node.port + " - " + node.intent); Channel ch = createChannel(node); if (ch.isOpen()) { successfulConnection = true; connectionListener.onSuccess.execute(); } ch.closeFuture().sync(); System.out.println("Connection to " + node.host + " closed.."); } catch (Exception e) { if (!successfulConnection) { //Don't notify a previously successful connection again.. connectionListener.onFailure.execute(); } throw new RuntimeException(e); } }
Example 5
Source File: NettyIoAcceptor.java From termd with Apache License 2.0 | 6 votes |
@Override public void unbind(SocketAddress address) { Channel channel = boundAddresses.get(address); if (channel != null) { ChannelFuture fut; if (channel.isOpen()) { fut = channel.close(); } else { fut = channel.closeFuture(); } try { fut.sync(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Example 6
Source File: NettyHandler.java From catalyst with Apache License 2.0 | 6 votes |
@Override public void exceptionCaught(ChannelHandlerContext context, final Throwable t) throws Exception { Channel channel = context.channel(); NettyConnection connection = getConnection(channel); if (connection != null) { try { if (channel.isOpen()) { channel.close(); } } catch (Throwable ignore) { } connection.handleException(t); } else { channel.close(); } }
Example 7
Source File: ConnectManager.java From nuls-v2 with MIT License | 6 votes |
public static Channel createConnect(String url) throws Exception { /* 如 果是第一次连接,则先放入集合 If it's the first connection, put it in the collection first */ Channel channel = NettyClient.createConnect(url); long start = NulsDateUtils.getCurrentTimeMillis(); while (channel==null || !channel.isOpen()) { if ( NulsDateUtils.getCurrentTimeMillis() - start > Constants.MILLIS_PER_SECOND * 5) { throw new Exception("Failed to connect " + url); } Thread.sleep(Constants.INTERVAL_TIMEMILLIS); } return channel; }
Example 8
Source File: HttpCacheClient.java From bazel with Apache License 2.0 | 6 votes |
@SuppressWarnings("FutureReturnValueIgnored") private void releaseDownloadChannel(Channel ch) { if (ch.isOpen()) { // The channel might have been closed due to an error, in which case its pipeline // has already been cleared. Closed channels can't be reused. try { ch.pipeline().remove(IdleTimeoutHandler.class); ch.pipeline().remove(HttpClientCodec.class); ch.pipeline().remove(HttpContentDecompressor.class); ch.pipeline().remove(HttpDownloadHandler.class); } catch (NoSuchElementException e) { // If the channel is in the process of closing but not yet closed, some handlers could have // been removed and would cause NoSuchElement exceptions to be thrown. Because handlers are // removed in reverse-order, if we get a NoSuchElement exception, the following handlers // should have been removed. } } channelPool.release(ch); }
Example 9
Source File: LionConnectionManager.java From lionrpc with Apache License 2.0 | 6 votes |
public void getConnectionAndSendRequest(RequestMessage request){ Channel channel = null; try { channel = connectionPoll.take(); while(channel != null){ if(channel.isOpen()){ channel.writeAndFlush(request); return; }else{ LOGGER.error("连接已经断开:"+channel.remoteAddress()); channel = connectionPoll.take(); } } } catch (Exception e) { LOGGER.error("getConnectionAndSendRequest happen exception.", e); }finally{ if(channel != null && channel.isOpen()){ connectionPoll.offer(channel); } } }
Example 10
Source File: HandlerRemovingChannelPool.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private void removePerRequestHandlers(Channel channel) { channel.attr(IN_USE).set(false); // Only remove per request handler if the channel is registered // or open since DefaultChannelPipeline would remove handlers if // channel is closed and unregistered // See DefaultChannelPipeline.java#L1403 if (channel.isOpen() || channel.isRegistered()) { removeIfExists(channel.pipeline(), HttpStreamsClientHandler.class, LastHttpContentHandler.class, FlushOnReadHandler.class, ResponseHandler.class, ReadTimeoutHandler.class, WriteTimeoutHandler.class); } }
Example 11
Source File: RemoterNonHA.java From jumbune with GNU Lesser General Public License v3.0 | 5 votes |
/** * Write to channel. * * @param channel the channel * @param magicBytes the magic bytes * @param pathOrCommand the path or command * @param attachment the attachment */ private void writeToChannel(Channel channel, String[] magicBytes, Object pathOrCommand, Object attachment) throws ConnectException { //update leader agent details // if (pathOrCommand instanceof CommandWritable // && ((CommandWritable) pathOrCommand).isCommandForMaster()) { // CommandWritable commandWritable = (CommandWritable) pathOrCommand; // AgentNode agent = ZKUtils.getLeaderAgentfromZK(); // commandWritable.setNameNodeHost(agent.getHost()); // if(commandWritable.isHasSshAuthKeysFile()){ // commandWritable.setSshAuthKeysFile(agent.getPrivateKey()); // } // } long firstAttempt = System.currentTimeMillis(); long timeOut = RemotingConstants.TEN * RemotingConstants.THOUSAND; while (!channel.isOpen() || !channel.isActive()) { if (System.currentTimeMillis() - firstAttempt >= timeOut) { try { throw new TimeoutException(); } catch (TimeoutException e) { logger.error("Waited for 10 sec for connection reattempt to JumbuneAgent, but failed to connect", e); } break; } } if (!channel.isActive()) { logger.warn("channel #" + channel.hashCode() + " still disconnected, about to write on disconnected Channel"); } if (attachment != null && attachment instanceof CyclicBarrier) { channel.attr(RemotingConstants.barrierKey).set((CyclicBarrier)attachment); }else if (attachment != null) { channel.attr(RemotingConstants.handlerKey).set((ChannelInboundHandler)attachment); } channel.write(Unpooled.wrappedBuffer(magicBytes[0].getBytes(), magicBytes[1].getBytes(), magicBytes[2].getBytes())); channel.write(pathOrCommand); channel.flush(); }
Example 12
Source File: NodeHandler.java From JLilyPad with GNU General Public License v3.0 | 5 votes |
@Override public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception { Channel channel = context.channel(); if(cause instanceof IOException) { if(!cause.getMessage().equals("Connection reset by peer")) { cause.printStackTrace(); } } else if (!(cause instanceof ReadTimeoutException)) { cause.printStackTrace(); } if(channel.isOpen()) { channel.close(); } }
Example 13
Source File: NettyServer.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 5 votes |
public static Result write(Object obj, String tenantId ,String uniId) { // 获取锁 Lock lock = ChannelMap.getChannelLock(tenantId); try { Channel channel = ChannelMap.getChannel(tenantId); if(channel != null){ lock.lock(); if(channel.isOpen()){ // 设置同步 CountDownLatch latch = new CountDownLatch(1); ServerHandler nettyServerHandler = (ServerHandler) channel.pipeline().get("handler"); nettyServerHandler.resetSync(latch,1); nettyServerHandler.setUnidId(uniId); //channel.writeAndFlush(obj).sync(); channel.writeAndFlush(Unpooled.copiedBuffer((obj + "$_").getBytes())); //同步返回结果 if (latch.await(60, TimeUnit.SECONDS)){ // printerServerHandler.setTimeout(0); return nettyServerHandler.getResult(); } //如果超时,将超时标志设置为1 //printerServerHandler.setTimeout(1); log.error("netty请求超时60s"); return new Result(2,"请求超时",null,null); }else{ return new Result(0,"客户端已关闭!",null,null); } } }catch (Exception e){ e.printStackTrace(); return new Result(0,"服务出错!",null,null); }finally { if (lock != null){ lock.unlock(); } } return new Result(0,"客户端没有连接!",null,null); }
Example 14
Source File: LinkMgr.java From Almost-Famous with MIT License | 5 votes |
public static Channel channelValidator(Session session) { Channel channel = session.getChannel(); if (null == channel || !channel.isOpen()) { removeSession(session.getSid()); log.error("sessin={} is close!", session.getSid()); return null; } return channel; }
Example 15
Source File: QueryTcpHandler.java From JLilyPad with GNU General Public License v3.0 | 5 votes |
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception { Channel channel = context.channel(); if(cause instanceof IOException) { if(!cause.getMessage().equals("Connection reset by peer")) { cause.printStackTrace(); } } else if (!(cause instanceof ReadTimeoutException)) { cause.printStackTrace(); } if(channel.isOpen()) { channel.close(); } }
Example 16
Source File: ConnectionPool.java From drift with Apache License 2.0 | 5 votes |
@Override public Future<Channel> getConnection(ConnectionParameters connectionParameters, HostAndPort address) { ConnectionKey key = new ConnectionKey(connectionParameters, address); while (true) { synchronized (this) { if (closed) { return group.next().newFailedFuture(new TTransportException("Connection pool is closed")); } Future<Channel> future; try { future = cachedConnections.get(key, () -> createConnection(key)); } catch (ExecutionException e) { throw new RuntimeException(e); } // connection is still opening if (!future.isDone()) { return future; } // check if connection is failed or closed Channel channel = future.getNow(); // channel can be null if the future was canceled if (channel != null && channel.isOpen()) { return future; } // remove dead connection from cache cachedConnections.asMap().remove(key, future); } } }
Example 17
Source File: AbstractWebSocketServerHandle.java From reactor-guice with Apache License 2.0 | 5 votes |
@Override public Mono<Void> onClose(CloseWebSocketFrame frame, Channel channel) { System.out.println("onClose" + channel); if (channel.isOpen() && channel.isActive()) { channel.close(); } return Mono.empty(); }
Example 18
Source File: RabbitmqOfflineInfoHelper.java From netty-chat with Apache License 2.0 | 5 votes |
@Override public void registerPull(Channel channel) { UserInfo userInfo = userInfos.get(channel); Connection connection = ConnectionUtil.getConnection(); try { com.rabbitmq.client.Channel connectionChannel = connection.createChannel(); Consumer consumer = new DefaultConsumer(connectionChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String s = new String(body, "UTF-8"); UserInfoManager.rwLock.readLock().lock(); try { if (channel.isOpen()) { channel.writeAndFlush(new TextWebSocketFrame(ChatProto.buildMessProto(userInfo.getId(), userInfo.getUsername(), s))); connectionChannel.basicAck(envelope.getDeliveryTag(), false); } else { throw new RuntimeException(); } } finally { UserInfoManager.rwLock.readLock().unlock(); } } }; consumers.put(channel, connectionChannel); connectionChannel.basicConsume("queue_" + userInfo.getId(), false, consumer); } catch (IOException e) { e.printStackTrace(); } }
Example 19
Source File: ApplicationContext.java From netty_push_server with BSD 2-Clause "Simplified" License | 4 votes |
/** * 更新发送设备信息到数据库 * * @param deviceId * @return */ private MessagePushedInfo getMessagePushedInfo(MessageInfo messageInfo, DeviceInfo deviceInfo) { if (messageInfo == null || deviceInfo == null) { return null; } // 獲取appinfo信息 AppInfo deviceAppInfo = apps.get(deviceInfo.getAppId()); AppInfo messageAppInfo = apps.get(messageInfo.getAppId()); if (deviceAppInfo != messageAppInfo) { return null; } // 判断设备是否离线 if (isDeviceOffline(deviceInfo)) { // 如果设备已经离线了 则关闭相应的channel ChannelDeviceInfo channelDeviceInfo = this.getChannelDeviceInfoFromCache(deviceInfo.getDeviceId()); if (channelDeviceInfo != null) { Channel channel = channelDeviceInfo.getChannel(); if (channel != null && channel.isOpen()) { channel.close().addListener(ChannelFutureListener.CLOSE); } } // 离线的消息就不需要发送了 直接保存到离线消息中 if (messageInfo.getIsOfflineShow() == MESSAGE_OFFLINE_SHOW_YES) { // 保存离线消息 this.saveMessageOffline(messageInfo.getMsgId(), deviceInfo.getDeviceId()); return null; } } else { MessagePushedInfo messagePushedInfo = getMessagePushedInfoFromCache(messageInfo.getMsgId(), deviceInfo.getDeviceId()); if (messagePushedInfo == null) { messagePushedInfo = new MessagePushedInfo(); messagePushedInfo.setDeviceId(deviceInfo.getDeviceId()); messagePushedInfo.setMsgId(messageInfo.getMsgId()); messagePushedInfo.setPushTime(new Date()); // 超时时间 0-无超时(认为发送即成功,无需客户端确认回执) if (messageInfo.getExpireTimes() == 0) { // 默认设置设备已经确认了 messagePushedInfo.setReceiptTime(new Date()); messagePushedInfo.setState(MESSAGE_PUSHED_STATE_RECEIPT); } else { messagePushedInfo.setState(MESSAGE_PUSHED_STATE_INIT); } this.addMessagePushedInfoToCache(deviceInfo.getDeviceId(), messagePushedInfo); } else if (messagePushedInfo.getState() == MESSAGE_PUSHED_STATE_RECEIPT) { // 已經回執過了 不需要再發送 return null; } return messagePushedInfo; } return null; }
Example 20
Source File: AbstractNettySession.java From sailfish-core with Apache License 2.0 | 4 votes |
private void disposeChannel(Channel channel) { if (channel.isOpen() && !channel.close().awaitUninterruptibly(5, TimeUnit.SECONDS)) { throw new ServiceException("Channel '" + getName() + "' has not been closed for 5 seconds"); } }