Re: Example for a simple Socket Server?



On Wed, Apr 19, 2017 at 3:16 PM Sven Wick <sven wick gmx de> wrote:
Hi,

I am currently experimenting with GJS
and try to do a simple socket server just for learning purposes.


This is what I have so far:


    const GLib = imports.gi.GLib
    const Gio = imports.gi.Gio;

    let s = new Gio.Socket({
            family: Gio.SocketFamily.IPV4,
            protocol: Gio.SocketProtocol.UDP,
            type: Gio.SocketType.DATAGRAM
    });

    let address = new Gio.InetSocketAddress({
            address: Gio.InetAddress.new_any(Gio.SocketFamily.IPV4),
            port: 4444,
    });

    s.init(null);

    s.bind(address, true);

    while(true) {

        let buf = GLib.ByteArray.new(256);

        for (let ii=0; (ii<256); ++ii) {
            buf[ii]= 0;
        }

        buf[256]= 0;

        let n = s.receive(buf, null );

        print(n);
        print(buf);
    }



I can connect to it via

  nc -u 127.0.0.1 4444


If I type in an "a" for example,
the socket server prints:

  2
  <blank>

So, it doesn't echo the input from netcat
and only prints the size of the input string.


Any idea what I'm doing wrong?

Hi Sven,

There's no GLib.ByteArray.new(length) constructor. What I believe is happening is that the "256" argument is getting ignored and you're getting a 0-length GLib.ByteArray, which isn't really a binding-friendly object and doesn't support JS indexing. I think that you're subsequently setting 256 _javascript_ properties on it, that are not visible to the C code that you're calling.

I would suggest to use GJS's native ByteArray:

    const ByteArray = imports.byteArray;
    ...etc...
    let buf = new ByteArray.ByteArray(256);

This _should_ work. However, it doesn't when I try it. I would suggest two things:

1. Write the equivalent C code of your test program, and if that works as expected, then please file a bug with GJS;
2. As a workaround, try using the methods of Gio.DatagramBased since Gio.Socket implements that interface. Gio.DatagramBased.receive_messages() looks like it might work for you.

Regards,
Philip C


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]