Skip to content

Instantly share code, notes, and snippets.

@yallie
Created February 24, 2016 12:28
Show Gist options
  • Save yallie/0af1aedef524c5f4b935 to your computer and use it in GitHub Desktop.
Save yallie/0af1aedef524c5f4b935 to your computer and use it in GitHub Desktop.
Sample IPC server for wrapping around the static class
// Compile this code using: csc ipctest.cs /r:Zyan.Communication.dll
// First run — starts server.
// Second run — starts client.
using System;
using System.Linq;
using System.Text;
using Zyan.Communication;
using Zyan.Communication.Protocols.Ipc;
struct Program
{
const string IpcPortName = "AnyValidFilename";
const string ZyanHostName = "SampleService";
static void Main()
{
try
{
RunServer();
}
catch // can't start two servers on the same port
{
RunClient();
}
}
// ------------------------------- Shared code --------
public interface ISampleService
{
string GeneratePassword(int length);
}
// ------------------------------- Client code --------
static void RunClient()
{
var protocol = new IpcBinaryClientProtocolSetup();
var url = protocol.FormatUrl(IpcPortName, ZyanHostName);
using (var conn = 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 = proxy.GeneratePassword(length);
Console.WriteLine("Server generated password: {0}", password);
}
}
}
// ------------------------------- Server code --------
static void RunServer()
{
var protocol = new IpcBinaryServerProtocolSetup(IpcPortName);
using (var host = new ZyanComponentHost(ZyanHostName, protocol))
{
host.RegisterComponent<ISampleService, SampleService>();
Console.WriteLine("Server started. Press ENTER to quit.");
Console.ReadLine();
}
}
static class StaticService
{
public static 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();
}
}
internal class SampleService : ISampleService
{
public string GeneratePassword(int length)
{
return StaticService.GeneratePassword(length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment