Can't receive from Gio.Socket in javascript

I’m adding a new method to a GObject of mine that launches a child process and returns a Gio.Socket that allows to communicate with the child. Now I’m trying to use it from Javascript, but can’t make it work. I’m using this piece of code to read what the child process sends:

let data = new Uint8Array(40);
let r = mysocket.receive(data, null);

At return, r contains 19, which is exactly the number of bytes I sent from the other process, but data contains all zeros.

If I return the FD instead of a Gio.Socket, and use that FD to create a UnixInputStream, I receive the data correctly, which means that the children is sending everything fine, and the problem must be in how I’m calling the receive method in the socket. I tried using a GLib.Bytes and GLib.ByteArray, but they aren’t accepted…

What am I doing wrong?

EDIT: setting the size of the array to 10 it reads only 10 bytes from the socket, but again the array contains ten '0’s, so it seems that the call to receive correctly detects the array size, but simply doesn’t store the data inside…

I’m not 100% on this, but I believe the issue here is that GJS/JavaScript doesn’t have a mutable buffer type like in C. There are a few vfuncs in the Gio stream APIs you can’t implement for this reason. Even though you can pass in a TypedArray and don’t get an error, they don’t work the same.

FWIW, if this is a subprocess you’re launching I find it much easier just to use Gio.Subprocess and use the provided stdin/stdout pipe functions. You can queue reads/writes using the streams’ async functions and let them do the waiting in the task thread.

I usually only use GSocket functions directly when I need to do things like grab the remote address from a UDP socket, so I pass the peek flag to avoid eating the socket message and then queue a read on a stream wrapping the socket.

2 Likes

Thanks for the answer. Yes, that is what I was suspecting, but I presumed that it was a bug in Javascript.

About using stdin/stdout, I’m already using Gio.Subprocess under the hood, and exposing it, but I wanted to add this for those cases where you need extra communication ways.

I modified it and now it returns a SimpleIOStream, using the same FD in both InputStream and OutputStream and works fine, but I’m not sure if this can result in problems…

Oh I see, this is for your new shell subprocess thingy. It’s looking good by the way :slight_smile:

I think it should be okay and as long as there’s access to the FD, someone using it should be able to workaround any special use case they have.

1 Like

Yes, it is about it. And since both streams are UnixStreams, it is still possible to get access to the FDs if needed.

Thanks!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.