I have an interface in C#, something like this:
interface ITest
{
int Method1(int something);
}
All methods have parameters of basic types (integer, string, enum).
Now I want the implementation and the client to run on different machines communicating over a socket. What I could do manually is to make an implementation like this:
class Test : ITest
{
int Method1(int something)
{
m_Serializer.Serialize(something, m_Socket);
int result = (int)m_Serializer.Deserialize(m_Socket, typeof(int));
return result;
}
}
Is there a way to automate it, i.e. to generate such a wrapper for a given interface automatically?
I could generate it manually via Reflection.Emit, but that’s quite complex. Any easy way?
WCF (Windows Communication Foundation) would be what you’re looking for. It does pretty much exactly this – it does however have a somewhat steep learning curve.
I like to think of it as a framework that automatically generates a network “protocol” that is defined by your interface – the service contract. The “protocol” is also independent of the underlying network transport – there are bindings for raw TCP, HTTP, HTTPS, all with different use cases in mind.
You never have to actually care about what the network traffic actually looks like at the protocol or byte level – the whole lot is done for you seamlessly.
Clever stuff, worth learning.
Complete example of a WCF client and server over plain TCP, with no config files (all programmatic)
Create a class library which will be shared between two other programs, your client and server, containing an interface.
In program one, the server:
Add a reference to the class library above.
Program two, the client:
Add a reference to the class library above.