我希望能夠在服務器應用程序和客戶端應用程序之間進行通信。這兩個應用程序都是用C#/ WPF編寫的。接口位於一個單獨的DLL中,兩個應用程序都有一個對它的引用。發送消息到其他進程
在接口DLL是IDataInfo接口看起來像:
Serializer<IDataInfo> serializer = new Serializer<IDataInfo>();
IDataInfo dataInfo = new DataInfo(HEADERBYTES, CONTENTBYTES);
Process clientProcess = Process.Start("Client.exe", serializer.Serialize(dataInfo));
客戶端的應用程序得到:
public interface IDataInfo
{
byte[] Header { get; }
byte[] Data { get; }
}
服務器應用程序通過下面的代碼調用客戶端來自服務器的消息:
Serializer<IDataInfo> serializer = new Serializer<IDataInfo>();
IDataInfo dataInfo = serializer.Deserialize(string.Join(" ", App.Args));
Serializer-Class只是一個通用的c使用Soap-Formatter序列化/反序列化的lass。該代碼看起來像:
public class Serializer<T>
{
private static readonly Encoding encoding = Encoding.Unicode;
public string Serialize(T value)
{
string result;
using (MemoryStream memoryStream = new MemoryStream())
{
SoapFormatter soapFormatter = new SoapFormatter();
soapFormatter.Serialize(memoryStream, value);
result = encoding.GetString(memoryStream.ToArray());
memoryStream.Flush();
}
return result;
}
public T Deserialize(string soap)
{
T result;
using (MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(soap)))
{
SoapFormatter soapFormatter = new SoapFormatter();
result = (T)soapFormatter.Deserialize(memoryStream);
}
return result;
}
}
直到這裏一切工作正常。服務器創建客戶端,客戶端可以反序列化它的參數IDataInfo
-Object。
現在我想能夠從服務器發送消息到正在運行的客戶端。我在Interface-DLL中引入了IClient接口,方法爲void ReceiveMessage(string message);
MainWindow.xaml.cs正在實現IClient接口。
我的問題是現在我怎麼才能在我的服務器中獲得IClient對象,當我只有Process-Object時。我想過Activator.CreateInstance
,但我不知道如何做到這一點。我很確定我可以通過處理流程獲得IClient,但我不知道如何。
有什麼想法?
你需要使用某種通信方案。閱讀WCF。 –