问题
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:
Notice: I tried to change both response and its length, but the error is same in both situations.
回答1:
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.
Edit: 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;
来源:https://stackoverflow.com/questions/46301554/native-message-received-but-response-failed