Skip to content

Instantly share code, notes, and snippets.

@ashic
Last active December 27, 2015 18:39
Show Gist options
  • Save ashic/7371417 to your computer and use it in GitHub Desktop.
Save ashic/7371417 to your computer and use it in GitHub Desktop.
C# vs F# 0MQ sync REP server
public class Server
{
private readonly NetMQContext _context;
private readonly string _id;
public Server(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.Bind(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));
}
}
}
}
let server (ctx:NetMQContext, address, id, token:CancellationToken) =
let doWork (ready:Tasks.TaskCompletionSource<bool>) =
async {
use socket = ctx.CreateResponseSocket()
socket.Bind address
ready.SetResult true
while token.IsCancellationRequested = false do
let sender =
socket.Receive()
|> System.Text.Encoding.ASCII.GetString
do printfn "[%s] Got request from %s" id sender
Tasks.Task.Delay(2000, token).Wait token
DateTime.Now.ToString()
|> System.Text.Encoding.ASCII.GetBytes
|> socket.Send
}
let ready = new Tasks.TaskCompletionSource<bool>()
doWork ready
|> fun x -> Async.Start(x, token)
ready.Task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment