-
Notifications
You must be signed in to change notification settings - Fork 40
Getting Started
Tyler Jensen edited this page Sep 2, 2020
·
2 revisions
To get started with ServiceWire, you need three .NET projects. (You could get away with just two but that would be strange.)
- Service definition (interface and data contract classes
- Service host (implementation of interface and host)
- Service client
Install-Package ServiceWire
And here is some example code you might write to create, host and use a service over TCP.
In a shared assemly--your interface and data contracts
public interface IMyTester
{
Guid GetId(string source, double weight, int quantity);
TestResponse Get(Guid id, string label, double weight, out int quantity);
List<string> GetItems(Guid id, int[] vals);
}
[Serializable]
public struct TestResponse
{
public Guid Id { get; set; }
public string Label { get; set; }
public long Quantity { get; set; }
}
On the server--your interface implementation and hosting
public class MyTester : IMyTester
{
private string longLabel = string.Empty;
private const int totalKilobytes = 140;
private Random rand = new Random(DateTime.Now.Millisecond);
public MyTester()
{
var sb = new StringBuilder();
for (int i = 0; i < totalKilobytes; i++)
{
for (int k = 0; k < 1024; k++) sb.Append(((char)rand.Next(32, 126)));
}
longLabel = sb.ToString();
}
public Guid GetId(string source, double weight, int quantity)
{
return Guid.NewGuid();
}
public TestResponse Get(Guid id, string label, double weight, out int quantity)
{
quantity = 44;
return new TestResponse { Id = id, Label = longLabel, Quantity = quantity };
}
public List<string> GetItems(Guid id, int[] vals)
{
var list = new List<string>();
list.Add("42");
list.Add(id.ToString());
list.Add("MyTest");
list.Add(longLabel);
return list;
}
}
static void Main(string[] args)
{
// logger and stats are optional
// there is a null implementation by default
var logger = new Logger(logLevel: LogLevel.Debug);
var stats = new Stats();
var port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
var ipEndpoint = new IPEndPoint(IPAddress.Any, port);
var mytester = new MyTester();
var tcphost = new TcpHost(ipEndpoint, logger, stats);
tcphost.AddService<IMyTester>(mytester);
tcphost.Open();
Console.WriteLine("Press Enter to stop the dual host test.");
Console.ReadLine();
tcphost.Close();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
On the client--easy
private static void Main(string[] args)
{
var ip = ConfigurationManager.AppSettings["ip"];
var port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
var ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
using (var client = new TcpClient<IMyTester>(ipEndPoint))
{
for (int i = 0; i < 10; i++)
{
var id = client.Proxy.GetId("test1", 3.314, 42);
int q2 = 4;
var response = client.Proxy.Get(id, "mirror", 4.123, out q2);
var list = client.Proxy.GetItems(id, new int[] { 3, 6, 9 });
}
}
Console.ReadLine();
}
And that's all there is to it.