Keep on moving

あんまりまとまってないことを書きますよ

Playing pyuv

Good evening everyone!This post is English translation of here.

First

node.js which is server-side-Java Script is recently popular.
The library libuv for networks which the author of node.js is making is API of the libev style currently used on the back side of gevent.
The talk that Windows could also be used was heard, and since it seems to be pleasant, it used.

There was no document, and since I am poor at C, I looked for Python wrapper.
I found ↓.

https://github.com/saghul/pyuv

Install

It is not installable from the Pypi.

$ git clone https://github.com/saghul/pyuv.git
$ python setup.py build
$ sudo python setup.py install

Example

Execute TCP Echo Server.
Copying https://github.com/saghul/pyuv/blob/master/examples/echo-server-tcp.py

import os
import signal
import threading
import pyuv

def on_client_shutdown(client):
    client.close()
    clients.remove(client)

def on_read(client, data):
    if data is None:
        client.close()
        clients.remove(client)
        return
    data = data.strip()
    if not data:
        return
    client.write(data+os.linesep)
    client.shutdown(on_client_shutdown)

def on_connection(server):
    client = server.accept()
    clients.append(client)
    client.start_read(on_read)

def async_exit(async):
    [c.close() for c in clients]
    async.close()
    signal_h.close()
    server.close()

def signal_cb(sig, frame):
    async.send(async_exit)


print "PyUV version %s" % pyuv.__version__

loop = pyuv.Loop()

async = pyuv.Async(loop)
clients = []

server = pyuv.TCP(loop)
server.bind(("0.0.0.0", 5000))
server.listen(on_connection)

signal_h = pyuv.Signal(loop)
signal_h.start()

t = threading.Thread(target=loop.run)
t.start()

signal.signal(signal.SIGINT, signal_cb)
signal.pause()

t.join()

print "Stopped!"

Echo Server Benchmark

The benchmark was taken for methane/echoserver · GitHub to reference.
※ The execution result in VM
※ A server and a client are operated by the same VM. This is not good.
※ 4core 1024M Environment

f:id:Ehren:20111226005432p:image
Detail is Here

Speed is somewhat slow compared with Tornado. The design of pyuv resembles Tornado.

Conclusion

libuv can be easily used by using pyuv.
It is very fun.