Search in sources :

Example 66 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project web3sdk by FISCO-BCOS.

the class ChannelConnections method reconnect.

public void reconnect() {
    for (Entry<String, ChannelHandlerContext> ctx : networkConnections.entrySet()) {
        if (ctx.getValue() == null || !ctx.getValue().channel().isActive()) {
            String[] split = ctx.getKey().split(":");
            String host = split[0];
            Integer port = Integer.parseInt(split[1]);
            logger.debug("尝试连接到: {}:{}", host, port);
            bootstrap.connect(host, port);
        } else {
            logger.trace("发送心跳至 {}", ctx.getKey());
            // 连接还在,发送心跳
            EthereumMessage ethereumMessage = new EthereumMessage();
            ethereumMessage.setSeq(UUID.randomUUID().toString().replaceAll("-", ""));
            ethereumMessage.setResult(0);
            ethereumMessage.setType((short) 0x13);
            ethereumMessage.setData("0".getBytes());
            ByteBuf out = ctx.getValue().alloc().buffer();
            ethereumMessage.writeHeader(out);
            ethereumMessage.writeExtra(out);
            ctx.getValue().writeAndFlush(out);
        }
    }
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) EthereumMessage(org.bcos.channel.dto.EthereumMessage)

Example 67 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project web3sdk by FISCO-BCOS.

the class ChannelHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
    Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort();
    final ChannelHandlerContext ctxF = ctx;
    final ByteBuf in = (ByteBuf) msg;
    logger.trace("接收消息,来自" + host + ":" + port + " in:" + in.readableBytes());
    logger.trace("threadPool:{}", threadPool == null);
    try {
        if (threadPool == null) {
            connections.onReceiveMessage(ctx, in);
        } else {
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    connections.onReceiveMessage(ctxF, in);
                }
            });
        }
    } catch (RejectedExecutionException e) {
        logger.error("线程池已满,拒绝请求", e);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 68 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project web3sdk by FISCO-BCOS.

the class ChannelHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    try {
        // 已连上,获取ip信息
        String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
        Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort();
        logger.debug("已成功连接[" + host + "]:[" + String.valueOf(port) + "]," + String.valueOf(ctx.channel().isActive()));
        if (isServer) {
            logger.debug("server接收新连接: {}:{}", host, port);
            // 将此新连接增加到connections
            ConnectionInfo info = new ConnectionInfo();
            info.setHost(host);
            info.setPort(port);
            connections.getConnections().add(info);
            connections.setNetworkConnectionByHost(info.getHost(), info.getPort(), ctx);
            connections.getCallback().onConnect(ctx);
        } else {
            // 更新ctx信息
            ChannelHandlerContext connection = connections.getNetworkConnectionByHost(host, port);
            if (connection != null && connection.channel().isActive()) {
                logger.debug("连接已存在且有效 关闭重连: {}:{}", host, port);
                ctx.channel().disconnect();
                ctx.channel().close();
            } else {
                logger.debug("client成功连接 {}:{}", host, port);
                connections.setNetworkConnectionByHost(host, port, ctx);
                connections.getCallback().onConnect(ctx);
            }
        }
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 69 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project web3sdk by FISCO-BCOS.

the class ConnectionPair method retrySendRemoteMessage.

public void retrySendRemoteMessage() {
    Integer errorCode = 0;
    try {
        // 选取客户端节点
        logger.debug("远端节点数:{}", remoteConnectionInfos.size());
        remoteConnectionInfo = null;
        if (remoteConnectionInfos.size() > 0) {
            Random random = new Random();
            Integer index = random.nextInt(remoteConnectionInfos.size());
            logger.debug("选取:{}", index);
            remoteConnectionInfo = remoteConnectionInfos.get(index);
            remoteConnectionInfos.remove(remoteConnectionInfos.get(index));
        }
        if (remoteConnectionInfo == null) {
            // 所有节点已尝试,无法再重试了
            logger.error("发送消息失败,所有重试均失败");
            errorCode = 99;
            throw new Exception("发送消息失败,所有重试均失败");
        }
        ChannelHandlerContext ctx = remoteChannelConnections.getNetworkConnectionByHost(remoteConnectionInfo.getHost(), remoteConnectionInfo.getPort());
        remoteConnection = ctx;
        if (ctx != null && ctx.channel().isActive()) {
            ByteBuf out = ctx.alloc().buffer();
            message.writeHeader(out);
            message.writeExtra(out);
            ctx.writeAndFlush(out);
            logger.debug("发送消息至  " + remoteConnectionInfo.getHost() + ":" + String.valueOf(remoteConnectionInfo.getPort()) + " 成功");
        } else {
            logger.error("发送节点不可用");
            retrySendRemoteMessage();
        }
    } catch (Exception e) {
        logger.error("发送消息异常", e);
        ChannelResponse response = new ChannelResponse();
        response.setErrorCode(errorCode);
        response.setErrorMessage(e.getMessage());
        // 找不到连接,错误
        logger.error("发送连接异常,返回错误99");
        if (message.getType() == 0x20 || message.getType() == 0x21) {
            message.setType((short) 0x21);
        } else if (message.getType() == 0x30 || message.getType() == 0x31) {
            message.setType((short) 0x31);
        } else {
        // ethereum消息,不用改类型
        }
        message.setResult(99);
        ByteBuf out = localConnection.alloc().buffer();
        message.writeHeader(out);
        message.writeExtra(out);
        localConnection.writeAndFlush(out);
        // 彻底失败后,删掉这个seq
        if (message.getSeq() != null) {
            server.getSeq2Connections().remove(message.getSeq());
        }
        if (timeout != null) {
            timeout.cancel();
        }
        return;
    }
}
Also used : Random(java.util.Random) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelResponse(org.bcos.channel.dto.ChannelResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 70 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project web3sdk by FISCO-BCOS.

the class Server method onLocalMessage.

public void onLocalMessage(ChannelHandlerContext ctx, Message message) {
    try {
        logger.debug("处理来自SDK请求: " + message.getSeq());
        ChannelHandlerContext remoteCtx = null;
        ConnectionPair pair = seq2Connections.get(message.getSeq());
        if (pair != null) {
            // 已有这个seq,发往远端的响应
            logger.debug("已有seq");
            // 发送到远端的响应
            remoteCtx = pair.remoteConnection;
            if (message.getType() != 0x31) {
                pair.localConnection = ctx;
            }
            ByteBuf out = remoteCtx.alloc().buffer();
            message.writeHeader(out);
            message.writeExtra(out);
            logger.debug("消息发送至:{}:{}", ((SocketChannel) remoteCtx.channel()).remoteAddress().getAddress().getHostAddress(), ((SocketChannel) remoteCtx.channel()).remoteAddress().getPort());
            remoteCtx.writeAndFlush(out);
        } else {
            pair = new ConnectionPair();
            pair.localConnection = ctx;
            pair.setServer(this);
            pair.setMessage(message);
            // 本地发往远程的消息,如果是链上链下,需要按给定的nodeID发
            if (message.getType() == 0x20 || message.getType() == 0x21) {
                // 获取nodeID
                logger.debug("链上链下消息一期 指定目的地");
                if (message.getData().length < 256) {
                    logger.error("错误的channel消息 长度不足256:{}", message.getData().length);
                }
                // 获取nodeID对应的连接,检查可用性
                String nodeID = new String(message.getData(), 128, 128);
                logger.debug("转发至:{}", nodeID, message.getData());
                for (ConnectionInfo conn : remoteConnections.getConnections()) {
                    if (conn.getNodeID().equals(nodeID)) {
                        remoteCtx = remoteConnections.getNetworkConnectionByHost(conn.getHost(), conn.getPort());
                        pair.remoteConnection = remoteCtx;
                        break;
                    }
                }
                if (remoteCtx == null || !remoteCtx.channel().isActive()) {
                    // 找不到连接,错误
                    logger.error("发送连接异常,返回错误99");
                    if (message.getType() == 0x20 || message.getType() == 0x21) {
                        message.setType((short) 0x21);
                    } else {
                        message.setType((short) 0x31);
                    }
                    message.setResult(99);
                    ByteBuf out = ctx.alloc().buffer();
                    message.writeHeader(out);
                    message.writeExtra(out);
                    ctx.writeAndFlush(out);
                    return;
                }
                ByteBuf out = remoteCtx.alloc().buffer();
                message.writeHeader(out);
                message.writeExtra(out);
                logger.debug("消息发送至:{}:{}", ((SocketChannel) remoteCtx.channel()).remoteAddress().getAddress().getHostAddress(), ((SocketChannel) remoteCtx.channel()).remoteAddress().getPort());
                remoteCtx.writeAndFlush(out);
                pair.init();
            } else {
                logger.debug("其它消息,使用ConnectionPair逻辑");
                pair.setRemoteChannelConnections(remoteConnections);
                List<ConnectionInfo> remoteConnectionInfos = new ArrayList<ConnectionInfo>();
                remoteConnectionInfos.addAll(remoteConnections.getConnections());
                pair.setRemoteConnectionInfos(remoteConnectionInfos);
                seq2Connections.put(message.getSeq(), pair);
                pair.init();
                pair.retrySendRemoteMessage();
            }
        }
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionInfo(org.bcos.channel.handler.ConnectionInfo) ByteBuf(io.netty.buffer.ByteBuf) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)661 Channel (io.netty.channel.Channel)274 ByteBuf (io.netty.buffer.ByteBuf)234 ChannelFuture (io.netty.channel.ChannelFuture)210 Test (org.junit.Test)208 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)201 Bootstrap (io.netty.bootstrap.Bootstrap)177 InetSocketAddress (java.net.InetSocketAddress)160 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)156 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)154 Test (org.junit.jupiter.api.Test)153 ChannelPipeline (io.netty.channel.ChannelPipeline)151 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)141 AtomicReference (java.util.concurrent.atomic.AtomicReference)140 IOException (java.io.IOException)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)120 ClosedChannelException (java.nio.channels.ClosedChannelException)119 CountDownLatch (java.util.concurrent.CountDownLatch)115 ArrayList (java.util.ArrayList)113 List (java.util.List)111