gpt4 book ai didi

firefox - Rust不接受来自本地消息传递的标准输入-FireFox

转载 作者:行者123 更新时间:2023-12-03 11:37:23 31 4
gpt4 key购买 nike

我正在使用web API从Firefox开发一个 native 消息传递应用程序。该扩展应该调用一个解析stdin的应用程序,然后基于它解析的一些数据调用我的另一个rust应用程序,但是出于显而易见的原因,该rust应用程序不接受来自firefox的输入(当我执行此操作时,手动)。
这是扩展的代码:

/*
On a click on the browser action, send the app a message.
*/
browser.browserAction.onClicked.addListener(() => {
console.log("Sending: ping");
var sending = browser.runtime.sendNativeMessage(
"themefox_manager",
"ping");
sending.then(onResponse, onError);
});


function onResponse(response) {
console.log("Received " + response);
}


function onError(error) {
console.log(`Error: ${error}`);
}

这是rust应用程序的代码:

use std::fs;
use std::io;
use std::io::prelude::*;

fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let mut file = fs::File::create("/home/user/filename.txt").unwrap();
//
if line.unwrap() == "ping" {
file.write_all(b"TEST").expect("Error");
}
}
}


奇怪的是,当我关闭Firefox时(而不是在应用启动时),我的主目录中的文本文件首次出现。而且它也没有文字TEST。

谢谢你的帮助!

干杯

最佳答案

我设法从this crate提出了自己的解决方案。

快速说明:“如果您想跳过所有代码,并且立即要从模板存储库开始编码,请查看此解决方案的底部,您应该能够在其中找到更多信息。”

读取输入然后返回输入的代码如下:

pub fn read_input<R: Read>(mut input: R) -> io::Result<serde_json::Value> {
let length = input.read_u32::<NativeEndian>().unwrap();
let mut buffer = vec![0; length as usize];
input.read_exact(&mut buffer)?;
let json_val: serde_json::Value = serde_json::from_slice(&buffer).unwrap();
Ok(json_val)
}

代码的作用是读取输入,该输入将作为参数传递给函数,然后读取它,将其解析为json var并返回其成功/错误值。

该代码正在main.rs文件中使用,如下所示:

let json_val = match lib::read_input(io::stdin()) {
Err(why) => panic!("{}", why.to_string()),
Ok(json_val) => json_val,
};

在这里,输入作为参数传递给read_input函数。

为了发送代码,我使用了以下功能:
pub fn write_output<W: Write>(mut output: W, value: &serde_json::Value) -> io::Result<()> {
let msg = serde_json::to_string(value)?;
let len = msg.len();
// Chrome won't accept a message larger than 1MB
if len > 1024 * 1024 {
panic!("Message was too large", length: {}, len)
}
output.write_u32::<NativeEndian>(len as u32)?;
output.write_all(msg.as_bytes())?;
output.flush()?;
Ok(())
}

这将获取标准输出和作为参数传递的消息。然后,该函数将消息写入输出(通常为stdout,也可以是用于调试目的的文件)。

调用函数write_output的代码如下:

let response = serde_json::json!({ "msg": "pong" });
match lib::write_output(io::stdout(), &response) {
Err(why) => panic!("{}", why.to_string()),
Ok(_) => (),
};


该项目使用这些依赖项,因此请确保将它们添加到 Cargo.toml
    "byteorder" = "*"
"serde_json" = "*"

main.rs文件的导入为:
mod lib;
use std::io;

对于lib.rs文件,两个函数都驻留在其中:
extern crate serde_json;
use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::fs;
use std::io;
use std::io::{Read, Write};

我还创建了一个git模板仓库,以便您可以快速启动,可以找到它 here

关于firefox - Rust不接受来自本地消息传递的标准输入-FireFox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62126147/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com