本文將介紹如何輕松架起遠程客戶/服務器體系結構,讓您領略C#編成的帶來的無限精簡便利。
首先,實現服務器端。代碼分析如下:
//引入相應命名空間
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace ServerClass {
//實現一個服務器和客戶端將要共同進行通訊的類MyRemoteClass
public class MyRemoteClass: MarshalByRefObject
{
public MyRemoteClass() {
}
//這個方法是服務器和客戶端進行通訊的,當然也可以定義其他更多的方法
//客戶端傳送一個字符串過來
public bool SetString(String sTemp) {
try {
//服務器端打印客戶端傳過來的字符串。返回邏輯值
Console.WriteLine("This string '{0}' has a length of {1}", sTemp, sTemp.Length);
return sTemp != "";
} catch {
return false;
}
}
}
//服務器控制類,這個類只是為了控制啟動和關閉服務器的作用,你也可以把它的Main放到MyRemoteClass類中去。
public class MyServer {
public static void Main() {
//打開并注冊一個服務
TcpChannel chan = new TcpChannel(8085);
ChannelServices.RegisterChannel(chan);
RemotingConfiguration.RegisterWellKnownServiceType(
System.Type.GetType("ServerClass.MyRemoteClass"),
"RemoteTest", WellKnownObjectMode.SingleCall);
//保持運行
System.Console.WriteLine("Hit <enter> to exit...");
System.Console.ReadLine();
}
}
}
然后,實現客戶端。代碼分析如下:
//引入相應命名空間
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
//引入服務器和客戶端進行通訊的類MyRemoteClass
using ServerClass;
namespace ClientClass {
public class MyClient {
public static void Main() {
try {
//打開并注冊一個TCP通道
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
連接服務器,獲取通訊類
MyRemoteClass obj = (MyRemoteClass) Activator.GetObject(typeof(MyRemoteClass),
"tcp://localhost:8085/RemoteTest");
if (obj == null)
System.Console.WriteLine("Could not locate server");
else
if (obj.SetString("Sending String to Server"))
System.Console.WriteLine("Suclearcase/" target="_blank" >ccess: Check the other console to verify.");
else
System.Console.WriteLine("Sending the test string has failed.");
System.Console.WriteLine("Hit <enter> to exit...");
System.Console.ReadLine();
} catch (Exception exp) {
Console.WriteLine(exp.StackTrace);
}
}
}
}
編譯服務器代碼
csc csc /out:MyServer.exe MyServer.cs
編譯客戶端代碼
csc /r:MyServer.exe MyClient.cs
啟動服務器c:\>start MyServer
啟動客戶端c:\>MyClient