本文将介绍如何轻松架起远程客户/服务器体系结构,让您领略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("Success: 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
.Net把很多功能包装太好了,给程序员带来了很多便利,本文只是涉及了其中一个方面具体的应用。文中错误处请邮件联系[email protected] 
|