2012-09-27 29 views
2

我在C#這樣的接口,東西:如何通過套接字封送.Net接口?

interface ITest 
{ 
    int Method1(int something); 
} 

所有方法都有基本類型(整數,字符串,枚舉)的參數。

現在我希望實現和客戶端運行在通過套接字進行通信的不同計算機上。我可以做手工是讓這樣的實現:

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; 
    } 
} 

有沒有辦法將其自動化,即生成自動給定接口這樣的包裝?

我可以通過Reflection.Emit手動生成,但這非常複雜。任何簡單的方法?

+0

生成它如何?您是否期待套接字服務器接收一些數據並在接收數據時生成(通過Reflection.Emit)ITest的實現? –

+0

聽起來很適合遙控。 – leppie

+0

@Peter Ritchie生成一個將以「method name」「argument1」格式序列化的實現...服務器端將有一個實際實現的實例,並通過反射調用方法。 –

回答

3

WCF (Windows Communication Foundation)將是你在找什麼。它幾乎完全是這樣 - 它的確有一個陡峭的學習曲線。

我喜歡將其視爲一個框架,它會自動生成由您的界面(服務合同)定義的網絡「協議」。 「協議」也獨立於底層網絡傳輸 - 原始TCP,HTTP,HTTPS都有綁定,所有這些都考慮到不同的用例。

您從來不必真正關心網絡通信在協議或字節級別的實際外觀 - 整個過程都是無縫完成的。

聰明的東西,值得學習。

WCF客戶端和服務器通過純TCP,沒有配置文件(所有程序)

創建一個將其他兩個程序之間共享的類庫,您的客戶端和服務器,包含的完整示例接口。

[ServiceContract] 
public interface IMyApi 
{ 
    [OperationContract] 
    string SayHello(string s); 
} 

在方案一中,服務器:
添加到上面的類庫的引用。

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class MyApi : IMyApi 
{ 
    public string SayHello(string s) 
    { 
     return "Hello " + s; 
    } 
} 

static void Main() 
{ 
    var api = new MyApi(); 
    var svcHost = new ServiceHost(api, new Uri("net.tcp://localhost:12345/MyService")); 
    svcHost.Open(); 
    Thread.CurrentThread.Join(); 
} 

方案二,客戶端:
添加到上面的類庫的引用。

static void Main() 
{ 
    var binding = new NetTcpBinding(); 
    var endpoint = new EndpointAddress("net.tcp://localhost:12345/MyService"); 
    var cf = new ChannelFactory<IMyApi>(binding, endpoint); 
    var client = cf.CreateChannel(); 

    Console.WriteLine(client.SayHello("Tom")); // output on the console should be "Hello Tom" 
} 
+0

不要使用WCF,但如果你在.NET環境之外使用它,甚至有絲毫的可能性。那是......不那麼有趣。 – Robert

+0

WCF over HTTP(S)通過REST可以在非.NET環境下正常工作。只需使用不同的綁定('WebHttpbinding')。這裏有一個相當不錯的例子:http://saravananarumugam.wordpress.com/2011/03/04/simple-rest-implementation-with-webhttpbinding/ – tomfanning

2

雖然你可能只是自己的序列化數據(見Serialization)和反序列化的另一面,有更好的選擇。

Windows Communication Foundation是.NET框架中的一項技術,可以爲您處理此問題。它自動管理所有通信(套接字)以及跨多種傳輸技術傳輸對象。