先弄清一下流程吧:
?? 1>定義遠(yuǎn)程對象(繼承自MarshalByRefObject)
?? 2>創(chuàng)建一個(gè)Server端作為宿主(注冊通道、注冊遠(yuǎn)程對象)
?? 3>創(chuàng)建客戶端(注冊通道、通過URL獲取Server端的遠(yuǎn)程對象的代理、通過代理操作遠(yuǎn)程對象)
服務(wù)器IP:10.10.1.35?? 端口號:8090
如果使用的端口號已經(jīng)被占用會(huì)提示:
具體操作代碼:
?1.創(chuàng)建一個(gè)操作具體的項(xiàng)目RemotingModel
?
namespace RemotingModel { //記得把類的訪問修飾符改為public public class Talker : MarshalByRefObject//繼承自該MarshalByRefObject { public void Talk(string word) { Console.WriteLine(word); } } }
?
?2.添加一個(gè)服務(wù)器端項(xiàng)目RemotingServer:這個(gè)項(xiàng)目在服務(wù)器端10.10.1.35機(jī)器上
?? 1>添加引用System.Runtime.Remoting和RemotingModel項(xiàng)目
?? 2>添加如下代碼:
using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using RemotingModel;
?
static void Main(string[] args) { //注冊通道(添加引用RemotingModel和System.Runtime.Remoting) TcpServerChannel channel = new TcpServerChannel("TalkChannel", 8090); ChannelServices.RegisterChannel(channel, false); //注冊遠(yuǎn)程對象 RemotingConfiguration.RegisterWellKnownServiceType(typeof(Talker), "Ser_Talker", WellKnownObjectMode.SingleCall ); Console.ReadLine(); }
?
?3.添加一個(gè)客戶端項(xiàng)目RemotingClient:這個(gè)項(xiàng)目在客戶端機(jī)器上
??? 同樣添加那兩引用
??
using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using RemotingModel; namespace RemotingClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Talker _talker = null; private void button1_Click(object sender, EventArgs e) { //操作遠(yuǎn)程對象 _talker.Talk(txt_word.Text.Trim()); //Do other things txt_content.Text = "發(fā)送成功:" + txt_word.Text.Trim(); } private void Form1_Load(object sender, EventArgs e) { //注冊通道 TcpClientChannel channel = new TcpClientChannel(); ChannelServices.RegisterChannel(channel, false); //獲取遠(yuǎn)程對象 _talker = (Talker)Activator.GetObject(typeof(Talker), "TCP://10.10.1.35:80/Ser_Talker");//TCP://10.10.1.35:8090/Ser_Talker } } }
?注意:如果客戶端和服務(wù)器端ChannelServices.RegisterChannel(channel, true);這里是true的時(shí)候會(huì)報(bào)錯(cuò):
如果端口號寫的不一致就會(huì)出現(xiàn)如下錯(cuò)誤:
當(dāng)然如果客戶端和服務(wù)器端都在本機(jī)上運(yùn)行的時(shí)候這里的true也可以的。
生成之后你直接在服務(wù)器端和客戶端下打開bin>Debug>文件夾下的.exe就可以實(shí)現(xiàn)效果了。
這樣的話就ok了你在本機(jī)上發(fā)的消息馬上就能在服務(wù)器10.10.1.35上看到消息了。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
