Created
May 20, 2015 12:45
-
-
Save yallie/7d263d3a44c0c0936a7e to your computer and use it in GitHub Desktop.
Async/await example for Zyan Communication Framework
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
// Compile this code using: csc example.cs /r:Zyan.Communication.dll | |
// First run — starts server. | |
// Second run — starts client. | |
using System; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Zyan.Communication; | |
using Zyan.Communication.Protocols.Tcp; | |
struct Program | |
{ | |
const int TcpPortNumber = 8765; | |
const string ZyanHostName = "SampleService"; | |
static void Main() | |
{ | |
try | |
{ | |
RunServer(); | |
} | |
catch // can't start two servers on the same port | |
{ | |
RunClient().Wait(); | |
} | |
} | |
// ------------------------------- Shared code -------- | |
public interface ISampleService | |
{ | |
string GeneratePassword(int length); | |
} | |
// ------------------------------- Client code -------- | |
static async Task RunClient() | |
{ | |
var protocol = new TcpDuplexClientProtocolSetup(); | |
var url = protocol.FormatUrl("localhost", TcpPortNumber, ZyanHostName); | |
using (var conn = await Task.Run(() => new ZyanConnection(url, protocol))) | |
{ | |
Console.WriteLine("Connected to server."); | |
var proxy = conn.CreateProxy<ISampleService>(); | |
while (true) | |
{ | |
Console.Write("Enter password length (empty line to quit): "); | |
var line = Console.ReadLine().Trim(' ', '\r', '\n', '.', '-'); | |
if (string.IsNullOrEmpty(line) || line.Any(c => !char.IsNumber(c))) | |
{ | |
Console.WriteLine("Bye."); | |
break; | |
} | |
var length = Convert.ToInt32(line); | |
var password = await Task.Run(() => proxy.GeneratePassword(length)); | |
Console.WriteLine("Server generated password: {0}", password); | |
} | |
} | |
} | |
// ------------------------------- Server code -------- | |
static void RunServer() | |
{ | |
var protocol = new TcpDuplexServerProtocolSetup(TcpPortNumber); | |
using (var host = new ZyanComponentHost(ZyanHostName, protocol)) | |
{ | |
host.RegisterComponent<ISampleService, SampleService>(); | |
Console.WriteLine("Server started. Press ENTER to quit."); | |
Console.ReadLine(); | |
} | |
} | |
internal class SampleService : ISampleService | |
{ | |
public string GeneratePassword(int length) | |
{ | |
var sb = new StringBuilder(); | |
var rnd = new Random(); | |
for (var i = 0; i < length; i++) | |
{ | |
var @char = (char)('a' + rnd.Next('z' - 'a')); | |
sb.Append(@char); | |
} | |
Console.WriteLine("Generated password: {0}, length = {1}", | |
sb, length); | |
return sb.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment