SocketListener


Object Hierarchy:

Object hierarchy for SocketListener

Description:

[ Version ( since = "2.22" ) ]
public class SocketListener : Object

A SocketListener 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 add_address and add_inet_port. These will be listened on until close is called. Dropping your final reference to the SocketListener will not cause close to be called implicitly, as some references to the SocketListener may be held internally.

If you want to implement a network server, also look at SocketService and ThreadedSocketService which are subclasses of SocketListener that make this even easier.

Example: Socket Listener, sync:

Note:

Use telnet localhost 1024 or telnet localhost 1025 to create connections

Note:

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

All known sub-classes:

Namespace: GLib
Package: gio-2.0

Content:

Properties:

Creation methods:

Methods:

Signals:

Inherited Members: