轻松架起远程C-S体系

本文将介绍如何轻松架起远程客户/服务器体系结构,让您领略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

 1<enter> to exit...");   
 2System.Console.ReadLine();   
 3}   
 4}   
 5} 
 6
 7然后,实现客户端。代码分析如下:   
 8//引入相应命名空间   
 9using System;   
10using System.Runtime.Remoting.Channels;   
11using System.Runtime.Remoting.Channels.Tcp;   
12//引入服务器和客户端进行通讯的类MyRemoteClass   
13using ServerClass; 
14
15namespace ClientClass {   
16public class MyClient {   
17public static void Main() {   
18try {   
19//打开并注册一个TCP通道   
20TcpChannel chan = new TcpChannel();   
21ChannelServices.RegisterChannel(chan);   
22连接服务器,获取通讯类   
23MyRemoteClass obj = (MyRemoteClass) Activator.GetObject(typeof(MyRemoteClass),   
24"tcp://localhost:8085/RemoteTest");   
25if (obj == null)   
26System.Console.WriteLine("Could not locate server");   
27else   
28if (obj.SetString("Sending String to Server"))   
29System.Console.WriteLine("Success: Check the other console to verify.");   
30else   
31System.Console.WriteLine("Sending the test string has failed.");   
32System.Console.WriteLine("Hit <enter> to exit...");   
33System.Console.ReadLine();   
34} catch (Exception exp) {   
35Console.WriteLine(exp.StackTrace);   
36}   
37}   
38}   
39}   
40编译服务器代码   
41csc csc /out:MyServer.exe MyServer.cs   
42编译客户端代码   
43csc /r:MyServer.exe MyClient.cs   
44启动服务器c:\&gt;start MyServer   
45启动客户端c:\&gt;MyClient 
46
47.Net把很多功能包装太好了,给程序员带来了很多便利,本文只是涉及了其中一个方面具体的应用。文中错误处请邮件联系 [email protected]</enter></enter>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus