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

百般思念 提交于 2019-12-24 15:03:58

问题


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

    }

回答1:


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, e.g.,

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

HTH, Gerd



来源:https://stackoverflow.com/questions/26777852/gjs-how-to-read-a-socket-stream-in-gnome-shell-extension-using-g-data-input-stre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!