Хост для обмена сообщениями Chrome VB.Net - PullRequest
0 голосов
/ 20 сентября 2018

Мне было нелегко найти какую-либо поддержку для узлов Chrome Native Messaging в VB.Net, после долгих проб и ошибок я собрал что-то, что работает для одного сообщения за раз.Однако я не смог заставить работать

While OpenStandardStreamIn() IsNot Nothing

часть.Если у кого-то есть какие-либо предложения ...

ИНОГДА ЭТОТ КОДЕКС РАБОТАЕТ ОТЛИЧНО, для всех, кто, как я, ищет собственный хост сообщений VB.Net:

Кроме того, здесь используется Newtonsoft.Json Lib дляСериализация JSON ...

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.Runtime.InteropServices


Module Module1

Public Sub Main(ByVal args As String())

    'create response as an array so it can be easily converted JSON
    Dim ResponseString() As String = {""}

    ' get input from chrome extension
    Dim InputString As String = OpenStandardStreamIn()

    ' Do whatever you want with Input, then prepare Response
    ResponseString(0) = DO_SOMETHING(InputString)

    ' Send Response to Chrome
    OpenStandardStreamOut(ResponseString)

End Sub

Public Function OpenStandardStreamIn() As String
    Dim MsgLength As Integer = 0
    Dim InputData As String = ""
    Dim LenBytes As Byte() = New Byte(3) {} 'first 4 bytes are length

    Dim StdIn As System.IO.Stream = Console.OpenStandardInput() 'open the stream
    StdIn.Read(LenBytes, 0, 4) 'length
    MsgLength = System.BitConverter.ToInt32(LenBytes, 0) 'convert length to Int

    Dim Buffer As Char() = New Char(MsgLength - 1) {} 'create Char array for remaining bytes

    Using Reader As System.IO.StreamReader = New System.IO.StreamReader(StdIn) 'Using to auto dispose of stream reader
        While Reader.Peek() >= 0 'while the next byte is not Null
            Reader.Read(Buffer, 0, Buffer.Length) 'add to the buffer

        End While
    End Using

    InputData = New String(Buffer) 'convert buffer to string

    Return InputData
End Function

Private Sub OpenStandardStreamOut(ByVal ResponseData() As String) 'fit the response in an array so it can be JSON'd

    Dim OutputData As String = ""
    Dim LenBytes As Byte() = New Byte(3) {} 'byte array for length
    Dim Buffer As Byte() 'byte array for msg

    OutputData = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseData) 'convert the array to JSON

    Buffer = System.Text.Encoding.UTF8.GetBytes(OutputData) 'convert the response to byte array
    LenBytes = System.BitConverter.GetBytes(Buffer.Length) 'convert the length of response to byte array

    Using StdOut As System.IO.Stream = Console.OpenStandardOutput() 'Using for easy disposal

        StdOut.WriteByte(LenBytes(0)) 'send the length 1 byte at a time
        StdOut.WriteByte(LenBytes(1))
        StdOut.WriteByte(LenBytes(2))
        StdOut.WriteByte(LenBytes(3))

        For i As Integer = 0 To Buffer.Length - 1 'loop the response out byte at a time
            StdOut.WriteByte(Buffer(i))
        Next

    End Using
End Sub
End Module

В расширении Chrome откройте соединение, отправьте сообщение, и после получения ответа хост закроется.Посмотрите на нашей странице разработчика Chrome пример приложения / расширения: https://developer.chrome.com/apps/nativeMessaging

Я надеюсь, что это кому-нибудь поможет, и, пожалуйста, дайте мне знать, если вы сделаете какие-либо улучшения!

1 Ответ

0 голосов
/ 22 июня 2019
 Sub Main() ' Recursive Version
    Try
        Dim stdin As Stream = Console.OpenStandardInput()
        Dim stdout As Stream = Console.OpenStandardOutput()

        Dim MsgLength As Integer = 0
        Dim InputData As String = ""
        Dim LenBytes As Byte() = New Byte(3) {}
        stdin.Read(LenBytes, 0, 4)
        MsgLength = BitConverter.ToInt32(LenBytes, 0)
        Dim Buffer As Byte() = New Byte(MsgLength - 1) {}
        stdin.Read(Buffer, 0, Buffer.Length)
        InputData = Encoding.UTF8.GetString(Buffer)

        Dim Str As String = Newtonsoft.Json.JsonConvert.SerializeObject("[" & Now & "] Arrrr!")
        Dim buff() As Byte = Encoding.UTF8.GetBytes(Str)
        stdout.Write(BitConverter.GetBytes(buff.Length), 0, 4)
        stdout.Write(buff, 0, buff.Length)
        Main()
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Oh, Snap!")
    End Try
End Sub
...