SocketListener
Object Hierarchy:
Description:
[ Version ( since = "2.22" ) ]
public class SocketListener : Object
A `GSocketListener` is an object that keeps track of a set of server sockets and helps you accept sockets from any of the socket, either sync or async.
Add addresses and ports to listen on using [method@Gio.SocketListener.add_address] and [method@Gio.SocketListener.add_inet_port]. These will be listened on until [method@Gio.SocketListener.close] is called. Dropping your final reference to the `GSocketListener` will not cause [ method@Gio.SocketListener.close] to be called implicitly, as some references to the `GSocketListener` may be held internally.
If you want to implement a network server, also look at [class@Gio.SocketService] and [class@Gio.ThreadedSocketService] which are subclasses of `GSocketListener` that make this even easier.
Example: Socket Listener, sync:
Use telnet localhost 1024
or telnet localhost 1025
to create connections
Send "shutdown" to close the server.
public class Source : Object {
public uint16 port { private set; get; }
public Source (uint16 port) {
this.port = port;
}
}
public class Worker : Object {
private SocketConnection connection;
private Cancellable cancellable;
private Source source;
public Worker (SocketConnection connection, Source source, Cancellable cancellable) {
this.cancellable = cancellable;
this.connection = connection;
this.source = source;
}
public int run () {
try {
print ("Thread started (Port: %d)\n", this.source.port);
// Wait for a message:
DataInputStream istream = new DataInputStream (this.connection.input_stream) ;
string message = istream.read_line (null, this.cancellable);
print ("Received: %s\n", message);
stdout.flush ();
// Response:
OutputStream ostream = this.connection.output_stream;
ostream.write (message.data, this.cancellable);
ostream.write ("\n".data, this.cancellable);
if (message._strip () == "shutdown") {
this.cancellable.cancel ();
}
} catch (IOError e) {
print ("IOError: %s\n", e.message);
}
return 0;
}
}
public static int main (string[] args) {
try {
SocketListener listener = new SocketListener ();
// Used to shutdown the program:
Cancellable cancellable = new Cancellable ();
// Listen on port 1024 and 1025.
// Source is used as source-identifier.
listener.add_inet_port (1024, new Source (1024));
listener.add_inet_port (1025, new Source (1025));
SocketConnection? connection = null;
Object? source = null;
// Wait for connections:
while ((connection = listener.accept (out source, cancellable)) != null) {
// Spawn a thread for each request:
Worker worker = new Worker (connection, source as Source, cancellable);
new Thread<int>.try (null, () => { return worker.run (); });
connection = null;
}
} catch (Error e) {
print ("Error: %s\n", e.message);
}
return 0;
}
valac --pkg gio-2.0 GLib.SocketListener.accept.vala --target-glib=2.32