1、首先建立一個類。
using System;
using System.Windows.Forms;
namespace lei
{
public class rmb : MarshalByRefObject
{
public rmb()
{
MessageBox.Show("成功建立通道", "消息提示");
}
public string cli()
{
return "與伺服器端完成通信";
}
public void ser(string msg)
{
Console.WriteLine("用戶端資訊是:" + msg);
}
}
}
2、服務端(控制台程式):
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using lei;
namespace remoting
{
class Program
{
/// <summary>
/// 應用程式的主入口點。
/// </summary>
static TcpServerChannel channel;
[STAThread]
static void Main(string[] args)
{
channel = new TcpServerChannel(38);//注冊服務端的38端口
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(rmb), "dc", WellKnownObjectMode.Singleton);
Console.WriteLine("伺服器已經啟動");
Console.Read();
}
}
}
3、 用戶端FORM.CS(窗體)
using System;
using System.Windows.Forms;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using lei;
namespace client
{
public partial class Form1 : Form
{
rmb leis;
TcpClientChannel channelc;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string xx = textBox1.Text.ToString();
leis.ser(xx); //
// this.textBox1.Text = leis.cli();
}
private void Form1_Load(object sender, EventArgs e)
{
channelc = new TcpClientChannel();
ChannelServices.RegisterChannel(channelc, false);
leis = (rmb)Activator.GetObject(typeof(rmb), "tcp://localhost:38/dc"); //對應服務端的端口
}
}
}