Last active
November 18, 2016 19:48
-
-
Save yallie/d39a2e81106dc5572f1e2b5f519510eb to your computer and use it in GitHub Desktop.
Zyan delegate registration example
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
// http://zyan.com.de | |
// | |
// Compile using: csc test.cs /r:Zyan.Communication.dll | |
// | |
// Start up test.exe several times. | |
// The first process is the server, the rest are clients. | |
// | |
using System; | |
using System.Collections.Concurrent; | |
using Zyan.Communication; | |
using Zyan.Communication.Protocols.Tcp; | |
class Program | |
{ | |
static void Main() | |
{ | |
try | |
{ | |
StartServer(); | |
} | |
catch | |
{ | |
StartClient(); | |
} | |
} | |
// ------------ Server code -------------- | |
static void StartServer() | |
{ | |
var proto = new TcpDuplexServerProtocolSetup(4321); | |
using (var host = new ZyanComponentHost("DelegateTest", proto)) | |
{ | |
host.RegisterComponent<IService, Service>(); | |
Console.WriteLine("Server started. Press ENTER to quit."); | |
Console.ReadLine(); | |
} | |
} | |
public class Service : IService | |
{ | |
private static ConcurrentDictionary<Guid, Action> Callbacks { get; } = | |
new ConcurrentDictionary<Guid, Action>(); | |
private Guid ClientID | |
{ | |
get { return ServerSession.CurrentSession.SessionID; } | |
} | |
public void RegisterCallback(Action callback) | |
{ | |
// register my delegate | |
Callbacks[ClientID] = callback; | |
Console.WriteLine("Client {0} registered the delegate.", ClientID); | |
} | |
public void DoCallback() | |
{ | |
Action action; | |
if (Callbacks.TryGetValue(ClientID, out action)) | |
{ | |
// call my delegate, if registered | |
action(); | |
Console.WriteLine("Calling client {0}'s delegate.", ClientID); | |
} | |
} | |
} | |
// ------------ Shared code -------------- | |
public interface IService | |
{ | |
void RegisterCallback(Action callback); | |
void DoCallback(); | |
} | |
// ------------ Client code -------------- | |
static void StartClient() | |
{ | |
var proto = new TcpDuplexClientProtocolSetup(); | |
var url = proto.FormatUrl("localhost", 4321, "DelegateTest"); | |
using (var conn = new ZyanConnection(url)) | |
{ | |
var callback = new Action(() => | |
Console.WriteLine("This code was called by server!")); | |
var proxy = conn.CreateProxy<IService>(); | |
proxy.RegisterCallback(callback); | |
Console.WriteLine("Client started. Hit ENTER to test, ^C to quit."); | |
while (true) | |
{ | |
Console.ReadLine(); | |
proxy.DoCallback(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment