Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error when communicating with the native messaging host. #607

Closed
Scharfsinnig opened this issue Jun 18, 2021 · 6 comments
Closed

Error when communicating with the native messaging host. #607

Scharfsinnig opened this issue Jun 18, 2021 · 6 comments

Comments

@Scharfsinnig
Copy link

Scharfsinnig commented Jun 18, 2021

I'm confused by this error. I have already checked my manifest and reg settings. However, the error was still occurred.

image
image
image

# crx_python.py
"""
chrome extension messaging with local application.
"""
import sys
import struct
import json
import logging
from queue import Queue
import threading
import time


def read_message(queue):
    ctl = CrxToLocal()
    
    while True:
        ctl.set_message()
        ctl.send_message()
        print(">>>>> 发送信息......")
        logging.info(">>>>> 正在发送信息......")

        # print(">>>>> 正在接收数据......")
        # logging.info(">>>>> 正在接收数据......")
        # ctl.read_message()

        # ctl.handle_message()
        # logging.info(">>>>> 正在处理数据......")
        # print(">>>>> 正在处理数据......")
        time.sleep(3)


def main():
    # 主函数入口
    print(">>>>>>>>>>>>> starting......")
    # 1.对windows平台的行结束符处理:\r\n--->\n
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

    # 2.日志文件处理对象
    logging.basicConfig(
        filename="ctl.log",
        level=logging.INFO,
        format="%(levelname)s::%(asctime)s-%(module)s-%(lineno)d: %(message)s",
        datefmt="%Y-%d-%m %H:%M:%S")

    # 3.与chrome extension进行通信
    try:
        queue = Queue()
        threading.Thread()
        thread = threading.Thread(target=read_message, args=(queue,))
        thread.daemon = False
        thread.start()
    except Exception as e:
        logging.error(e)
        print(e)


# Chrome extension to local application:与chrome-extension进行通信的class
class CrxToLocal(object):
    def __init__(self):
        self._input_body = None
        self._output_body = None

    def read_message(self):
        # 读取标准输入流中的msg-header(first 4 bytes).
        text_length_bytes = sys.stdin.buffer.read(4)

        # Unpack message length as 4 byte integer, tuple = struct.unpack(fmt, buffer).
        text_length = struct.unpack("I", text_length_bytes)[0]

        # 读取标准输入流中的msg-body bytes
        self._input_body = sys.stdin.buffer.read(text_length)

    def set_message(self):
        self._output_body = "rpa,rpa,rpa".encode("utf-8")

    def handle_message(self):
        """更多处理对输入输出数据的操作..."""

        # 将chrome extension发送过来的数据保存到本地
        print(">>>>> get from big man:> {}".format(self._input_body))
        with open("./local_file.json", "a", encoding="utf-8") as f:
            json.dump(json.loads(self._input_body, encoding="utf-8"), f, ensure_ascii=False, indent=2)
        
        # _output_body的数据格式要求为JSON utf-8 bytes
        self._output_body = json.dumps({"response": "Nice to meet you."}).encode("utf-8")

    def send_message(self):
        # 将msg-header写到标准输出流, I表示int类型占4个字节,相关内容查看文档介绍python-doc/library/struct
        sys.stdout.buffer.write(struct.pack("I", len(self._output_body)))
        # 将msg-body写到标准输出流
        sys.stdout.buffer.write(self._output_body)
        sys.stdout.flush()


if __name__ == "__main__":
    main()
@guest271314

This comment was marked as off-topic.

@guest271314

This comment was marked as off-topic.

@Scharfsinnig
Copy link
Author

Is the Python file set as executable?

yes

@guest271314

This comment was marked as off-topic.

@guest271314

This comment was marked as off-topic.

@dotproto
Copy link
Contributor

Closing this issue as it is not a bug or feature request for the chrome-extension-samples repository. I don't mind if you two continue to try to work through the problem, but @Scharfsinnig, I'd encourage you to post future questions on the chromium-extensions Google Group or on StackOverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants