tinymq / client / tinymq_client.py

#!/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()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.