Skip to content

Instantly share code, notes, and snippets.

@ashic
Created November 7, 2013 12:33
Show Gist options
  • Save ashic/7353879 to your computer and use it in GitHub Desktop.
Save ashic/7353879 to your computer and use it in GitHub Desktop.
public class Worker
{
private readonly NetMQContext _context;
private readonly string _id;
public Worker(NetMQContext context, string id)
{
_context = context;
_id = id;
}
public Task Start(CancellationToken token, string address)
{
var ready = new TaskCompletionSource<bool>();
Task.Factory.StartNew(() => start(token, address, ready), token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
return ready.Task;
}
private void start(CancellationToken token, string address, TaskCompletionSource<bool> ready)
{
using (var socket = _context.CreateResponseSocket())
{
socket.Connect(address);
ready.SetResult(true);
while (token.IsCancellationRequested == false)
{
var bytes = socket.Receive();
var sender = Encoding.ASCII.GetString(bytes);
Console.WriteLine("[{0}] Received request from {1}", _id, sender);
Task.Delay(TimeSpan.FromSeconds(3), token).Wait(token);
var message = string.Format("{0} says {1}.", _id, DateTime.Now);
socket.Send(Encoding.ASCII.GetBytes(message));
}
}
}
}
@ptrelford
Copy link

module NetMQSample

open NetMQ
open System
open System.Text
open System.Threading

let run id (context:NetMQContext) (address:string) = async {
use socket = context.CreateResponseSocket()
socket.Connect(address)
while true do
let bytes = socket.Receive()
let sender = Encoding.ASCII.GetString(bytes)
printfn "%s received from %s" sender id
do! Async.Sleep(3000)
let message = sprintf "%s says %O" id (DateTime.Now)
socket.Send(Encoding.ASCII.GetBytes(message))
}

let context = NetMQContext.Create()
let id = "A"
do
use source = new CancellationTokenSource()
let work = run id context "tcp:128.0.0.1"
do Async.Start(work , source.Token)
System.Console.ReadLine() |> ignore
do source.Cancel()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment