Created
June 10, 2011 12:28
-
-
Save reuben/1018752 to your computer and use it in GitHub Desktop.
Actor-like syntax for ZMQ sockets in Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.zeromq.ZMQ; | |
import org.zeromq.ZMQActor; | |
class Player extends ZMQActor { | |
String name | |
int myNum | |
public Player(ZMQ.Context ctx, String addr, String name) { | |
super(ctx, ZMQ.REQ) | |
this.name = name | |
connect(addr) | |
} | |
void act() { | |
loop { | |
myNum = new Random().nextInt(10) | |
send myNum | |
react { | |
switch (it) { | |
case "too large": | |
println "$name: $myNum was too large" | |
break | |
case "too small": | |
println "$name: $myNum was too small" | |
break | |
case "you win": | |
println "$name: I won $myNum"; terminate() | |
} | |
} | |
} | |
} | |
} | |
def ctx = ZMQ.context(1) | |
new Player(ctx, "tcp://localhost:54321", "Player").start() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.zeromq.ZMQ; | |
import org.zeromq.ZMQActor; | |
class GameMaster extends ZMQActor { | |
int secretNum | |
public GameMaster(ZMQ.Context ctx, String addr) { | |
super(ctx, ZMQ.REP) | |
bind(addr) | |
secretNum = new Random().nextInt(10) | |
} | |
void act() { | |
loop { | |
react { num -> | |
num = num.toInteger() | |
if (num > secretNum) | |
reply "too large" | |
else if (num < secretNum) | |
reply "too small" | |
else { | |
reply "you win" | |
terminate() | |
} | |
} | |
} | |
} | |
} | |
def ctx = ZMQ.context(1) | |
new GameMaster(ctx, "tcp://*:54321").start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment