本文將介紹如何輕松架起遠(yuǎn)程客戶/服務(wù)器體系結(jié)構(gòu),讓您領(lǐng)略C#編成的帶來的無限精簡便利 。首先,實(shí)現(xiàn)服務(wù)器端 。代碼分析如下:
//引入相應(yīng)命名空間
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace ServerClass {
//實(shí)現(xiàn)一個(gè)服務(wù)器和客戶端將要共同進(jìn)行通訊的類MyRemoteClass
public class MyRemoteClass: MarshalByRefObject
{
; public MyRemoteClass() {
; }
; //這個(gè)方法是服務(wù)器和客戶端進(jìn)行通訊的,當(dāng)然也可以定義其他更多的方法
; //客戶端傳送一個(gè)字符串過來
; public bool SetString(String sTemp) {
; try {
//服務(wù)器端打印客戶端傳過來的字符串 。返回邏輯值
; Console.WriteLine("This string "{0}" has a length of {1}", sTemp, sTemp.Length);
return sTemp != "";
; } catch {
return false;
}
; }
;}
【輕松架起遠(yuǎn)程C-S體系】//服務(wù)器控制類,這個(gè)類只是為了控制啟動(dòng)和關(guān)閉服務(wù)器的作用,你也可以把它的Main放到MyRemoteClass類中去 。
;public class MyServer {
; public static void Main() {
//打開并注冊一個(gè)服務(wù)
TcpChannel chan = new TcpChannel(8085);
; ChannelServices.RegisterChannel(chan);
; RemotingConfiguration.RegisterWellKnownServiceType(
;System.Type.GetType("ServerClass.MyRemoteClass"),
;;"RemoteTest", WellKnownObjectMode.SingleCall);
; //保持運(yùn)行
; System.Console.WriteLine("Hit
; System.Console.ReadLine();
}
;}
}
然后,實(shí)現(xiàn)客戶端 。代碼分析如下:
//引入相應(yīng)命名空間
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
//引入服務(wù)器和客戶端進(jìn)行通訊的類MyRemoteClass
using ServerClass;
namespace ClientClass {
;public class MyClient {
; public static void Main() {
try {
;//打開并注冊一個(gè)TCP通道
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
連接服務(wù)器,獲取通訊類
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
; System.Console.ReadLine();
} catch (Exception exp) {
Console.WriteLine(exp.StackTrace);
; }
; }
;}
}
編譯服務(wù)器代碼
csc csc /out:MyServer.exe MyServer.cs
編譯客戶端代碼
csc /r:MyServer.exe MyClient.cs
啟動(dòng)服務(wù)器c:>start MyServer
啟動(dòng)客戶端c:>MyClient
推薦閱讀
- mysql如何開啟遠(yuǎn)程連接 mysql如何開啟遠(yuǎn)程連接服務(wù)器
- mysql怎么設(shè)置遠(yuǎn)程連接數(shù)據(jù)庫 遠(yuǎn)程訪問mysql數(shù)據(jù)庫設(shè)置
- 如何遠(yuǎn)程訪問mysql數(shù)據(jù)庫文件 如何遠(yuǎn)程訪問mysql數(shù)據(jù)庫
- 怎么遠(yuǎn)程訪問mysql數(shù)據(jù)庫 遠(yuǎn)程訪問mysql數(shù)據(jù)庫軟件
- Mysql怎么開啟遠(yuǎn)程連接 mysql怎么開啟遠(yuǎn)程連接服務(wù)
- win2003服務(wù)器修改遠(yuǎn)程登陸端口方法
- php 輕松架設(shè)本地服務(wù)器并實(shí)現(xiàn)管理方法
- MS09-018:Active Directory存在遠(yuǎn)程執(zhí)行代碼漏洞
- CentOS如何安裝XRDP實(shí)現(xiàn)遠(yuǎn)程桌面訪問
- Linux下定制SSH來簡化遠(yuǎn)程訪問教程 linux如何使用ssh命令遠(yuǎn)程登錄
