pyliblo - Example Code

Just some useless code to show what you can do with pyliblo.

Also take a look at the send_osc and dump_osc scripts, for tiny but functional examples.

Client Side

# send all messages to port 1234 on the local machine
try:
    target = liblo.Address(1234)
except liblo.AddressError, err:
    print str(err)
    sys.exit()

# send message "/foo/message1" with int, float and string arguments
liblo.send(target, "/foo/message1", 123, 456.789, "test")

# send double, int64 and char
liblo.send(target, "/foo/message2", ('d', 3.1415), ('h', 2**42), ('c', 'x'))

# we can also build a message object first...
msg = liblo.Message("/foo/blah")
# ... append arguments later...
msg.add(123, "foo")
# ... and then send it
liblo.send(target, msg)

# send a list of bytes as a blob
blob = [4, 8, 15, 16, 23, 42]
liblo.send(target, "/foo/blob", blob)

Server Side

# create server, listening on port 1234
try:
    server = liblo.Server(1234)
except liblo.ServerError, err:
    print str(err)
    sys.exit()

def foo_bar_callback(path, args):
    print "received message '%s' with arguments '%d' and '%f'" % (path, args[0], args[1])

def foo_baz_callback(path, args, types, src, data):
    print "received message '%s'" % path
    print "blob contains %d bytes, user data was '%s'" % (len(args[0]), data)

def fallback(path, args, types, src):
    print "got unknown message '%s' from '%s'" % (path, src.get_url())
    for a, t in zip(args, types):
        print "argument of type '%s': %s" % (t, a)

# register method taking an int and a float
server.add_method("/foo/bar", 'if', foo_bar_callback)

# register method taking a blob, and passing user data to the callback
server.add_method("/foo/baz", 'b', foo_baz_callback, "blah")

# register a fallback for unhandled messages
server.add_method(None, None, fallback)

# loop and dispatch messages every 100ms
while True:
    server.recv(100)