Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

c++ - Native Message received, but response failed

I am developing a macOS application which can communicate with google chrome extension through native messaging.

I used google official documentation from here, so I received data from extension successfully (as is shown in below).

But when I tried to answer, I always get an error. My response is in JSON format and it is:

{
 "text":
        "Client Started"
}

I use swift for my viewController and Objective-c++ for native messaging:

ViewController.swift:

let stream = StreamReader()
override func viewDidLoad() {
    super.viewDidLoad()
    stream.getStream()
    stream.writeStream("{"text":"Client Started"}")
}

StreamReader.m:

- (void)WriteStream:(NSString *)JSONResponse {
    NSString *JSONResponseArray = [NSString stringWithFormat:@"%@", JSONResponse];
    std::string outMsg = [JSONResponseArray UTF8String];
    unsigned int len = outMsg.length();
    std::cout.write(reinterpret_cast<const char *>(&len), 4);
    std::cout << outMsg.data() << std::flush;
}

Error:

enter image description here

Notice: I tried to change both response and its length, but the error is same in both situations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should output the string's length info to stdout:

    unsigned int len = outMsg.length();
    std::cout<< char(len & 0xFF)
             << char(((len >> 8) & 0xFF))
             << char(((len >> 16) & 0xFF))
             << char(((len >> 24) & 0xFF));

Now you can write the string data to stdout.

Then use std::flush to immediately flush the data i.e. send the data from our native messaging host to destination extension. I have noticed that if we won't do so then this data won't be sent to the destination immediately.

std::cout << outMsg.data() << std::flush;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...