Source

tinymq / client / client.py

Full commit
#!/usr/bin/env python

import sys
import socket
import struct

class tinymq_client(object):
    GET = 0
    ACK = 1
    PUT = 2
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setblocking(1)

    def _send(self, format, data):
        return self.socket.send(struct.pack(format, data))

    def _recv(self, nbytes, format):
        return struct.unpack(format, self.socket.recv(nbytes))

    def connect(self):
        return self.socket.connect((self.ip, self.port))

    def get(self):
        self._send("I", self.GET)
        msg_id, msg_len = self._recv(12, "QI")
        msg_data = self.socket.recv(msg_len)
        return (msg_id, msg_data)

    def ack(self, message_id):
        self._send("I", self.ACK)
        self._send("Q", message_id)

    def put(self, message):
        msg_len = len(message)
        self._send("I", self.PUT)
        self._send("I", msg_len)
        self._send("%ss" % msg_len, message)
        msg_id, = self._recv(8, "Q")
        return msg_id

def test():
    c = tinymq_client("127.0.0.1", 5673)
    c.connect()
    for i in range(0, 1000):
        c.put("test%s" % i)
    for i in range(0, 1000):
        msg_id, msg_data = c.get()
        print msg_id, msg_data
        c.ack(msg_id)

if __name__ == "__main__":
    test()