.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
轻松架起远程C-S体系

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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




相关文章

相关软件