Skip to content

Instantly share code, notes, and snippets.

@dantman
Created April 2, 2013 07:06
Show Gist options
  • Save dantman/5290438 to your computer and use it in GitHub Desktop.
Save dantman/5290438 to your computer and use it in GitHub Desktop.
Ping-Pong STOMP server. Demonstrating stompest with gevent.
import logging, gevent
from gevent import monkey
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.sync import Stomp
## Ideally this code (or something like it) would work without the following two lines
monkey.patch_socket()
monkey.patch_select()
logging.basicConfig(level=logging.INFO)
CONFIG = StompConfig('tcp://localhost:61613')
## Drain stomp server of any PING and PONG messages currently being held
def drain():
client = Stomp(CONFIG)
client.connect()
client.subscribe('/queue/pong', {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
client.subscribe('/queue/ping', {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
while client.canRead(2):
frame = client.receiveFrame()
client.ack(frame)
drain()
## Ping Server
def ping():
def log(msg):
print '[Ping] %s' % msg
log('Connecting')
client = Stomp(CONFIG)
client.connect()
client.subscribe('/queue/pong', {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
for _ in xrange(1,6):
log('Sending PING')
client.send('/queue/ping', 'PING')
while True:
frame = client.receiveFrame()
client.ack(frame)
if frame.command == 'MESSAGE' and frame.body == 'PONG':
log('Got PONG')
break
else:
log('Got unknown message, continuing to wait')
log('Sending QUIT')
client.send('/queue/ping', 'QUIT')
log('Disconnecting')
client.disconnect()
## Pong server
def pong():
def log(msg):
print '[Pong] %s' % msg
log('Connecting')
client = Stomp(CONFIG)
client.connect()
client.subscribe('/queue/ping', {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
while True:
frame = client.receiveFrame()
client.ack(frame)
if frame.command == 'MESSAGE':
if frame.body == 'QUIT':
log('Got QUIT')
break
elif frame.body == 'PING':
log('Got PING, sending PONG')
client.send('/queue/pong', 'PONG')
log('Disconnecting')
client.disconnect()
## Spawn both servers and wait for them to both return
gevent.joinall([
gevent.spawn(ping),
gevent.spawn(pong),
])
print '[Global] Quitting'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment