简体   繁体   中英

gjs How to read a socket stream in Gnome Shell Extension using g_data_input_stream_read_line_async

I'm trying to write a Gnome-Shell extension that communicates with Arduino through a Socket Server. The Server and Arduino are running fine, but I'm stuck at the extension code that listens for incoming Server messages.

Since I need a non blocking approach, using read_line_async seems perfect.

However I can't manage to get it to work. Here's what i got so far (relevant part):

    let sockClient, sockConnection, output_reader, receivedline;

// connect to socket
    sockClient = new Gio.SocketClient();
    sockConnection = sockClient.connect_to_host("127.0.0.1:21567", null, null);


// read server socket

    output_reader = new Gio.DataInputStream({ base_stream: sockConnection.get_input_stream() });

    output_reader.read_line_async(0, null, _SocketRead, null);


// callback

    function _SocketRead() {

        let [lineout, charlength, error] = output_reader.read_line_finish();

        receivedline = lineout;
        // process received data

    }

The async function is started just fine and also _SocketRead gets called, when there's a line received from the server, but it fails to read the data with read_line_finish() .

I'm completely new to gio and Extension development so I might just miss something obvious.

To me it seems like read_line_finish() may be missing it's GAsyncResult parameter, but i've got no clue on how to implement it.

EDIT:

The Callback function and read_line_finish() were missing their parameters. Thanks to Gerd's answer I was able to make it work. Helped me to figure out the example linked in the GIO Reference under "Description". So here is the working code for comparison:

    let sockClient, sockConnection, output_reader, receivedline;

// connect to socket
    sockClient = new Gio.SocketClient();
    sockConnection = sockClient.connect_to_host("127.0.0.1:21567", null, null);


// read server socket

    output_reader = new Gio.DataInputStream({ base_stream: sockConnection.get_input_stream() });

    output_reader.read_line_async(0, null, _SocketRead, null);


// callback

    function _SocketRead(gobject, async_res, user_data) {

        let [lineout, charlength, error] = gobject.read_line_finish(async_res);

        receivedline = lineout;
        // process received data

    }

I am also new to GJS but a solid understanding of programming language led me to the following partial solution: According to the Gio DataStream reference You have to provide all required parameters to the method, eg,

let asyncResult = new Gio.SimpleAsyncResult();
let length;
let lineout = output_reader.read_line_finish(asyncResult, length);

HTH, Gerd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM