Search in sources :

Example 1 with ChannelResponse

use of org.fisco.bcos.channel.dto.ChannelResponse in project web3sdk by FISCO-BCOS.

the class Channel2Client method main.

public static void main(String[] args) throws Exception {
    if (args.length < parameterNum) {
        System.out.println("param: target topic total number of request");
        return;
    }
    String topic = args[0];
    Integer count = Integer.parseInt(args[1]);
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    logger.debug("init client");
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    System.out.println("3s ...");
    Thread.sleep(1000);
    System.out.println("2s ...");
    Thread.sleep(1000);
    System.out.println("1s ...");
    Thread.sleep(1000);
    System.out.println("start test");
    System.out.println("===================================================================");
    ChannelRequest request = new ChannelRequest();
    for (Integer i = 0; i < count; ++i) {
        Thread.sleep(2000);
        request.setToTopic(topic);
        request.setMessageID(service.newSeq());
        request.setTimeout(5000);
        String content = "request seq:" + request.getMessageID();
        request.setContent(content.getBytes());
        System.out.println(df.format(LocalDateTime.now()) + " request seq:" + request.getMessageID() + ", Content:" + request.getContent() + " content:" + Arrays.toString(request.getContentByteArray()));
        ChannelResponse response = service.sendChannelMessage2(request);
        System.out.println(df.format(LocalDateTime.now()) + "response seq:" + response.getMessageID() + ", ErrorCode:" + response.getErrorCode() + ", Content:" + response.getContent());
    }
}
Also used : ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ChannelRequest(org.fisco.bcos.channel.dto.ChannelRequest) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Service(org.fisco.bcos.channel.client.Service) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 2 with ChannelResponse

use of org.fisco.bcos.channel.dto.ChannelResponse in project web3sdk by FISCO-BCOS.

the class Channel2ClientBinNeedVerify method main.

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("param: target topic filename of request");
        return;
    }
    String topic = args[0];
    String filename = args[1];
    Integer count = 10;
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    logger.debug("init client");
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    System.out.println("3s ...");
    Thread.sleep(1000);
    System.out.println("2s ...");
    Thread.sleep(1000);
    System.out.println("1s ...");
    Thread.sleep(1000);
    System.out.println("start test");
    System.out.println("===================================================================");
    for (Integer i = 0; i < count; ++i) {
        Thread.sleep(2000);
        ChannelRequest request = new ChannelRequest();
        request.setToTopic(topic);
        request.setMessageID(service.newSeq());
        request.setTimeout(5000);
        /*设置为-128表示为传输二进制*/
        int flag = -128;
        byte[] byteflag = intToByteArray(flag);
        int filelength = filename.length();
        byte[] bytelength = intToByteArray(filelength);
        byte[] bytefilename = filename.getBytes();
        byte[] contentfile = toByteArrFromFile(filename);
        byte[] content = byteCat(byteCat(byteCat(byteflag, bytelength), bytefilename), contentfile);
        request.setContent(content);
        logger.info("msg:" + Arrays.toString(content));
        System.out.println(df.format(LocalDateTime.now()) + " request seq:" + String.valueOf(request.getMessageID()) + " content length:" + content.length);
        ChannelResponse response = service.sendChannelMessageForVerifyTopic(request);
        System.out.println(df.format(LocalDateTime.now()) + "response seq:" + String.valueOf(response.getMessageID()) + ", ErrorCode:" + response.getErrorCode() + ", Content:" + response.getContent());
        if (response.getErrorCode() != 0) {
            System.out.println("Error message" + response.getErrorMessage());
        }
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ChannelRequest(org.fisco.bcos.channel.dto.ChannelRequest) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Service(org.fisco.bcos.channel.client.Service) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 3 with ChannelResponse

use of org.fisco.bcos.channel.dto.ChannelResponse in project web3sdk by FISCO-BCOS.

the class PushCallback method onPush.

@Override
public void onPush(ChannelPush push) {
    System.out.println("onPush content length:" + push.getContent2().length);
    logger.debug("onPush content content:" + Arrays.toString(push.getContent2()));
    if (push.getContent2().length < 8) {
        String content = new String(push.getContent2());
        System.out.println("onPush content:" + content);
    } else {
        byte[] byteflag = subbytes(push.getContent2(), 0, 4);
        int flag = byteArrayToInt(byteflag);
        if (flag == -128) {
            byte[] bytelength = subbytes(push.getContent2(), 4, 4);
            int length = byteArrayToInt(bytelength);
            byte[] bytefilename = subbytes(push.getContent2(), 8, length);
            String filename = new String(bytefilename);
            System.out.println("filename length:" + length + " filename binary:" + Arrays.toString(bytefilename) + " filename:" + filename);
            int contentlength = push.getContent2().length - 8 - filename.length();
            byte[] content = subbytes(push.getContent2(), 8 + filename.length(), contentlength);
            getFileFromBytes(content, filename);
            System.out.println("save file:" + filename + " success");
        } else {
            String content = new String(push.getContent2());
            System.out.println("onPush  content:" + content);
        }
    }
    ChannelResponse response = new ChannelResponse();
    response.setContent("receive request seq:" + String.valueOf(push.getMessageID()));
    response.setErrorCode(0);
    push.sendResponse(response);
}
Also used : ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse)

Example 4 with ChannelResponse

use of org.fisco.bcos.channel.dto.ChannelResponse in project web3sdk by FISCO-BCOS.

the class ChannelResponseCallback2 method retrySendMessage.

public void retrySendMessage() {
    Integer errorCode = 0;
    try {
        // 选取客户端节点
        logger.debug("Number of local nodes:{}", fromConnectionInfos.size());
        setFromConnection(null);
        if (fromConnectionInfos.size() > 0) {
            Random random = new SecureRandom();
            Integer index = random.nextInt(fromConnectionInfos.size());
            logger.debug("selected index: {}, peer: {}", index, fromConnectionInfos.get(index));
            setFromConnection(fromConnectionInfos.get(index));
            fromConnectionInfos.remove(fromConnectionInfos.get(index));
        }
        if (getFromConnection() == null) {
            // 所有节点已尝试,无法再重试了
            logger.error("Failed to send message,all retry failed");
            errorCode = ChannelMessageError.NODES_UNREACHABLE.getError();
            throw new Exception(" Failed to send message,all retry failed ");
        }
        ChannelHandlerContext ctx = fromChannelConnections.getNetworkConnectionByHost(getFromConnection().getHost(), getFromConnection().getPort());
        if (ctx != null && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
            ByteBuf out = ctx.alloc().buffer();
            message.writeHeader(out);
            message.writeExtra(out);
            ctx.writeAndFlush(out);
            logger.debug("send message to  {}:{} success ", fromConnection.getHost(), fromConnection.getPort());
        } else {
            logger.debug("sending node unavailable");
            retrySendMessage();
        }
    } catch (Exception e) {
        logger.error("send message exception {}", e);
        ChannelResponse response = new ChannelResponse();
        response.setErrorCode(errorCode);
        response.setErrorMessage(e.getMessage());
        try {
            onResponseMessage(response);
        } catch (Exception ee) {
            logger.error("onResponseMessage error:{}", ee);
        }
        // 彻底失败后,删掉这个seq
        if (message.getSeq() != null) {
            service.getSeq2Callback().remove(message.getSeq());
        }
        if (timeout != null) {
            timeout.cancel();
        }
        return;
    }
}
Also used : Random(java.util.Random) SecureRandom(java.security.SecureRandom) SecureRandom(java.security.SecureRandom) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 5 with ChannelResponse

use of org.fisco.bcos.channel.dto.ChannelResponse in project web3sdk by FISCO-BCOS.

the class Service method checkTopicVerify.

public void checkTopicVerify(ChannelHandlerContext ctx, TopicVerifyMessage message) throws IOException {
    SocketChannel socketChannel = (SocketChannel) ctx.channel();
    logger.info("get rand value request ChannelResponse seq:{} msgtype:{} address:{} port:{}", message.getSeq(), message.getType(), socketChannel.remoteAddress().getAddress().getHostAddress(), socketChannel.remoteAddress().getPort());
    logger.info("get rand value request :{} length:{}", Arrays.toString(message.getData()), message.getLength());
    sendResponse2Node(ctx, message);
    String content = new String(message.getData());
    logger.info("content:{} content:{}", content, Arrays.toString(content.getBytes()));
    NodeRequestSdkVerifyTopic nodeRequestSdkVerifyTopic = ObjectMapperFactory.getObjectMapper().readValue(content, NodeRequestSdkVerifyTopic.class);
    String topic = nodeRequestSdkVerifyTopic.getTopic();
    String topicForCert = nodeRequestSdkVerifyTopic.getTopicForCert();
    String nodeid = nodeRequestSdkVerifyTopic.getNodeId();
    logger.info("topic:{} topicForCert:{} nodeid:{}", topic, topicForCert, nodeid);
    ChannelRequest request = new ChannelRequest();
    request.setToTopic(topicForCert);
    request.setMessageID(newSeq());
    request.setTimeout(5000);
    request.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
    String randValue = UUID.randomUUID().toString().replaceAll("-", "");
    TopicVerifyReqProtocol topicVerifyProtocol = new TopicVerifyReqProtocol();
    topicVerifyProtocol.setRandValue(randValue);
    topicVerifyProtocol.setTopic(topic);
    String jsonStr = ObjectMapperFactory.getObjectMapper().writeValueAsString(topicVerifyProtocol);
    logger.info("generate rand value jsonStr:{} topic:{} messageid:{}", jsonStr, request.getToTopic(), message.getSeq());
    byte[] bytes = topicVerify.getByteBuffByString(request.getToTopic(), jsonStr);
    request.setContent(bytes);
    asyncSendChannelMessage2(request, new ChannelResponseCallback2() {

        @Override
        public void onResponseMessage(ChannelResponse response) {
            logger.info("get response messageid:{}", response.getMessageID());
            try {
                checkSignForAmop(topic, String.valueOf(randValue), nodeid, ctx, response);
            } catch (IOException e) {
                logger.error("check sign for amop failed:{}", e);
            }
        }
    });
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NodeRequestSdkVerifyTopic(org.fisco.bcos.channel.protocol.NodeRequestSdkVerifyTopic) ChannelRequest(org.fisco.bcos.channel.dto.ChannelRequest) TopicVerifyReqProtocol(org.fisco.bcos.channel.protocol.TopicVerifyReqProtocol) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) IOException(java.io.IOException)

Aggregations

ChannelResponse (org.fisco.bcos.channel.dto.ChannelResponse)16 ChannelRequest (org.fisco.bcos.channel.dto.ChannelRequest)6 IOException (java.io.IOException)5 DateTimeFormatter (java.time.format.DateTimeFormatter)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 KeyStoreException (java.security.KeyStoreException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 NoSuchProviderException (java.security.NoSuchProviderException)4 CertificateException (java.security.cert.CertificateException)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 Service (org.fisco.bcos.channel.client.Service)4 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)4 ApplicationContext (org.springframework.context.ApplicationContext)4 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)4 ByteBuf (io.netty.buffer.ByteBuf)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 SocketChannel (io.netty.channel.socket.SocketChannel)2 ChannelMessage2 (org.fisco.bcos.channel.dto.ChannelMessage2)2 EventLogPushCallback (org.fisco.bcos.channel.event.filter.EventLogPushCallback)2