.NET Remoting 简单示例
不多说,直接上代码
定义一个实体类,此实体类单独定义在类库中,客户端和服务都要引用
1 using System; 2 3 namespace RemotingDemo 4 { 5 public class Student : MarshalByRefObject 6 { 7 public static event Action<Student> OnReviceMsg; 8 9 public string Name { get; set; } 10 public int Age { get; set; } 11 public string Sex { get; set; } 12 13 public void SetValue(string nama, int age, string sex) 14 { 15 this.Name = nama; 16 this.Age = age; 17 this.Sex = sex; 18 if (OnReviceMsg != null) 19 { 20 OnReviceMsg(this); 21 } 22 } 23 public override string ToString() 24 { 25 return string.Format("姓名:{0},年龄:{1},性别:{2}", Name, Age, Sex); 26 } 27 } 28 }
定义服务端:
1 using RemotingDemo; 2 using System; 3 using System.Runtime.Remoting; 4 using System.Runtime.Remoting.Channels; 5 using System.Runtime.Remoting.Channels.Tcp; 6 using System.Windows.Forms; 7 8 namespace RemotingServerDemo 9 { 10 public partial class Form1 : Form 11 { 12 public Form1() 13 { 14 InitializeComponent(); 15 } 16 17 private void Form1_Load(object sender, EventArgs e) 18 { 19 TcpChannel channel = new TcpChannel(1234); 20 ChannelServices.RegisterChannel(channel, false); 21 RemotingConfiguration.RegisterWellKnownServiceType(typeof(Student), "RemotingStudentService", WellKnownObjectMode.SingleCall); 22 Student.OnReviceMsg += (stu) => 23 { 24 if (this.InvokeRequired) 25 { 26 this.Invoke(new Action(()=> { this.textBox1.Text = stu.ToString(); })); 27 } 28 else 29 { 30 this.textBox1.Text = stu.ToString(); 31 } 32 33 }; 34 } 35 36 37 } 38 }
定义客户端:
1 using RemotingDemo; 2 using System; 3 using System.Runtime.Remoting.Channels; 4 using System.Runtime.Remoting.Channels.Tcp; 5 using System.Windows; 6 7 namespace WpfApplication11 8 { 9 /// <summary> 10 /// Window1.xaml 的交互逻辑 11 /// </summary> 12 public partial class Window1 : Window 13 { 14 public Window1() 15 { 16 InitializeComponent(); 17 } 18 TcpChannel channel = new TcpChannel(); 19 20 Student obj = (Student)Activator.GetObject(typeof(Student), "tcp://localhost:1234/RemotingStudentService"); 21 private void button_Click(object sender, RoutedEventArgs e) 22 { 23 24 if (obj == null) 25 { 26 this.label.Content = "不能创建remoting对象"; 27 } 28 obj.SetValue("王五", 12, "男"); 29 this.textBox.Text = obj.ToString(); 30 31 } 32 33 private void Window_Loaded(object sender, RoutedEventArgs e) 34 { 35 ChannelServices.RegisterChannel(channel, false); 36 } 37 } 38 }
服务端和客户端界面如图:


以上即为所有,刚接触,还需深入了解

浙公网安备 33010602011771号