Tải bản đầy đủ (.docx) (52 trang)

Activator trong .net remoting

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.2 MB, 52 trang )

Activator trong .net remoting

Ứng dụng sẽ cho phép chọn trên giao diện các chức năng sau:
1) – Gửi 1 thông báo nào đó tới toàn bộ client
2) – Gửi 1 thông báo nào đó tới 1 client nào đó
3) – Tắt toàn bộ chương trình Client
4) – Shutdown toàn bộ máy đang sử dụng chương trình Client
Ở đây Tôi sẽ kết hợp Timer để thiết lập trong khoảng thời gian bao nhiêu milisecond
thì sẽ gửi/ nhận thông tin….
Giao diện của Server sẽ như sau:

Giao diện của Client:

1


Giao diện Send Message (khi Server chọn chức năng gửi thông báo thì các client sẽ
tự động pop up giao diện này. Chỉ khi nào Active nó bằng cách bấm vào nút ở giữa
màn hình thì nó không hiển thị):

Khi Server thực hiện các thao tác : (như hình minh họa) Thì client sẽ nhận được
những thông tin tương Ứng
Ở đây còn 2 thao tác: Shutdown 1 máy client, Gửi thông điệp tới 1 client Tôi không
làm, Tôi dành cho các bạn làm. Chú ý cách làm tương tự như Đóng cửa sổ từng
client. Rất dễ, bạn chỉ cần chuyển đổi ProcessType (enum trong chương trình cho
Tôi tạo) là bạn sẽ thực hiện được 2 yêu cầu này một cách dễ dàng.
Các bạn chú ý là chức năng Tắt client cũng như Shutdown từng máy client bạn nên
hiển thị ListView cho phép chọn từng máy, hoặc chọn hết. Ở đây Tôi đã làm sẵn
giao diện tắt từng client. bạn ứng dụng làm lại cho Shutdown.
Cấu trúc Solution:



Coding tầng ProxyObject – bạn để ý enum ProcessType, ứng với mỗi chức năng bạn
chỉ cần đổi nó là ok:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ProxyObject
{
[Serializable]
public enum ProcessType
{
CLOSE_A_CLIENT_APPLICATION=100,
CLOSE_ALL_CLIENT_APPLICATION=101,
SEND_MESSAGE_TO_A_CLIENT = 102,
SEND_MESSAGE_TO_ALL_CLIENT = 103,
SHUTDOWN_A_CLIENT_COMPUTER = 104,
SHUTDOWN_ALL_CLIENT_COMPUTER = 105,
NONE=113


};
[Serializable]
public class ClientInfor
{
public string ClientName { get; set; }
public ProcessType Type { get; set; }
}

[Serializable]
public class MyProcess:MarshalByRefObject
{
private ArrayList listClient = new ArrayList();
public void addClient(ClientInfor client)
{
listClient.Add(client);
}
public void updateClientToClose(string clientName)
{
for (int i = 0; i < listClient.Count; i++)
{
ClientInfor c = listClient[i] as ClientInfor;
if (c.ClientName.Equals(clientName,
StringComparison.CurrentCultureIgnoreCase))
{
c.Type = ProcessType.CLOSE_A_CLIENT_APPLICATION;
break;
}
}
}
public void removeAllClient()
{
listClient.Clear();
}
public void removeClient(ClientInfor client)
{
listClient.Remove(client);
}
public void removeClientByName(string name)

{
for (int i = 0; i < listClient.Count; i++)


{
ClientInfor c = listClient[i] as ClientInfor;
if (c.ClientName.Equals(name, StringComparison.CurrentCultureIgnoreCase))
{
listClient.RemoveAt(i);
break;
}
}
}
public ArrayList ListClient
{
get
{
return listClient;
}
}
public ProcessType Type { get; set; }
}
}

Coding tầng Server:
Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using ProxyObject;
namespace ServerTier
{
public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}
TcpChannel tcpChannel = null;
MyProcess myProcess = null;
private void btnStart_Click(object sender, EventArgs e)
{
int port = 9999;
if (Int32.TryParse(txtPort.Text,out port) == false)
{
MessageBox.Show(“Invalid Port!”);
txtPort.SelectAll();
txtPort.Focus();
}

if (tcpChannel != null || ChannelServices.GetChannel(“tcp”) != null)
{
ChannelServices.UnregisterChannel(tcpChannel);
}
tcpChannel = new TcpChannel(port);
ChannelServices.RegisterChannel(tcpChannel,false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyProcess),
“MYPROCESS”, WellKnownObjectMode.Singleton);
Object o= Activator.GetObject(typeof(MyProcess), “tcp://localhost:” + port +
“/MYPROCESS”);
if (o != null)
{
myProcess = o as MyProcess;
btnStart.Enabled = false;
this.Text = “Start OK”;
}
}private void btnCloseAllClientApplication_Click(object sender, EventArgs e)
{
myProcess.Type = ProcessType.CLOSE_ALL_CLIENT_APPLICATION;
}private void btnCloseAClientApplication_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.myProcess = myProcess;


frm2.ShowDialog();
}private void btnSendMessageToAClient_Click(object sender, EventArgs e)
{}private void btnShutdownAllClientComputer_Click(object sender,
EventArgs e)
{

myProcess.Type = ProcessType.SHUTDOWN_ALL_CLIENT_COMPUTER;
}private void ShutdownAClientComputer_Click(object sender, EventArgs e)
{}
private void btnSendMessageToAllClient_Click(object sender, EventArgs e)
{
myProcess.Type = ProcessType.SEND_MESSAGE_TO_ALL_CLIENT;
}
}
}

Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProxyObject;
namespace ServerTier
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public MyProcess myProcess;

private void Form2_Load(object sender, EventArgs e)
{
listView1.Items.Clear();


foreach (ClientInfor client in myProcess.ListClient)
{
ListViewItem itm = new ListViewItem(client.ClientName);
itm.Tag = client;
listView1.Items.Add(itm);
}
}private void btnClose_Click(object sender, EventArgs e)
{
myProcess.Type = ProcessType.CLOSE_A_CLIENT_APPLICATION;
ListView.CheckedListViewItemCollection list = listView1.CheckedItems;
foreach (ListViewItem item in list)
{
ClientInfor client = item.Tag as ClientInfor;
myProcess.updateClientToClose(client.ClientName);
}
}
}
}

Coding tầng Client
Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using ProxyObject;
namespace ClientTier
{
public partial class Form1 : Form
{
public Form1()
{


InitializeComponent();
}
MyProcess myProcess = null;
Timer myTimer = null;
string myName=”x”;
public string getComputerName()
{
return System.Environment.MachineName
+”-“+ System.DateTime.Now.Millisecond;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string url=”tcp://”+txtServer.Text+”:”+txtPort.Text+”/MYPROCESS”;
RemotingConfiguration.RegisterWellKnownClientType(typeof(MyProcess),url
);

myName = getComputerName();
myProcess = new MyProcess();
ClientInfor infor = new ClientInfor()
{ ClientName=myName,Type=ProcessType.NONE};
myProcess.addClient(infor);
frmMessage frmMsg = new frmMessage();
int isACK = -1;
myTimer = new Timer();
myTimer.Enabled = true;
myTimer.Interval = 300;
myTimer.Start();
myTimer.Tick += delegate
{
switch (myProcess.Type)
{
case ProcessType.CLOSE_A_CLIENT_APPLICATION:
foreach (ClientInfor client in myProcess.ListClient)
{
if (client.ClientName.Equals(myName,
StringComparison.CurrentCultureIgnoreCase)
&& client.Type==ProcessType.CLOSE_A_CLIENT_APPLICATION)
{
Close();
myProcess.removeClientByName(myName);


}
}
break;
case ProcessType.CLOSE_ALL_CLIENT_APPLICATION:

Close();
myProcess.removeAllClient();
break;
case ProcessType.SEND_MESSAGE_TO_A_CLIENT:
break;
case ProcessType.SEND_MESSAGE_TO_ALL_CLIENT:
frmMsg.BackColor = Color.Red;
if (isACK==-1)
{
isACK = 0;
if (frmMsg.ShowDialog() == DialogResult.OK)
{
isACK = 1;
}
else
{
isACK = -1;
}
}
break;
case ProcessType.SHUTDOWN_A_CLIENT_COMPUTER:
foreach (ClientInfor client in myProcess.ListClient)
{
if (client.ClientName.Equals(myName,
StringComparison.CurrentCultureIgnoreCase) && client.Type ==
ProcessType.SHUTDOWN_A_CLIENT_COMPUTER)
{
System.Diagnostics.Process.Start(“shutdown”, “/s /t 0”);
myProcess.removeClientByName(myName);
}

}
break;
case ProcessType.SHUTDOWN_ALL_CLIENT_COMPUTER:
System.Diagnostics.Process.Start(“shutdown”, “/s /t 0”);
myProcess.removeAllClient();


break;
}};
btnConnect.Enabled = false;
}private void Form1_Load(object sender, EventArgs e)
{}
}
}

frmMessage.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace ClientTier
{
public partial class frmMessage : Form
{
public frmMessage()
{

InitializeComponent();
}private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void frmMessage_Load(object sender, EventArgs e)
{
}
}
}

Trong project này không hiểu chỗ nào bạn có thể email hoặc comment trực tiếp, Tôi sẽ giải thích


—————————————————————————
Source
Code : />uter.rar
—————————————————————————
Chúc các bạn thành công.
Chia sẻ lên:





inShare





Print


Posted in: .Net Remoting C#

Ví dụ mẫu .Net Remoting & Windows Services
By Trần Duy Thanh on March 12, 2012 | 2 Comments

2 Votes

VÍ DỤ NÀY TÔI TÁCH LÀM 2 PHẦN (Sử dụng Visual Studio 2010, coding bằng
C#).


Phần 1: Tôi hướng dẫn các bạn cách thực hiện .Net Remoting. Sẽ có 3 Project trong
solution này. Tầng ProxyObject, tầng Server và tầng Client. Trong đó tầng Server sẽ
có giao diện để Start Stop Server, Tầng Client có giao diện để kết nối tới Server để
gọi một số phương thức trong tầng ProxyObject.
Phần 2: Tiếp tục với ví dụ trong phần 1, nhưng trong trường hợp này Tôi sẽ không
tạo giao diện cho tầng Server, mà Tôi đưa tầng Server về chạy theo dạng Windows
Services.
Tôi nghĩ rằng Topic này sẽ rất hữu ích cho những bạn muốn quan tâm tới các
chương trình .Net Remoting, Windows Services, cách sử dụng component Eventlog,
cũng như cách làm deployed chương trình. Vì Tôi hướng dẫn chi tiết nên có thể bạn
cảm thấy làm nó dài và phức tạp, nhưng thực ra nếu khi các bạn làm hiểu rành rồi thì
chỉ cần 5-10 phút là xong tầng Service và Setup. Chúc các bạn thành công.
Link download hướng
dẫn: />owsServices.docx

Link download source

code: />owsServices.rar

——————————————————————————————————
—————————–
Dưới đây là các bước chi tiết cho phần 1:
Bước 1: Tạo tên Solution
Bước 2: Tiến hành tạo 3 Project cho Solution: Tầng ProxyObject, tầng Server và
Client
Bước 3: Tiến hành viết coding cho tầng ProxyObject
Bước 4: Tiến hành viết coding cho tầng Server
Bước 5: Tiến hành viết code cho Tầng Client


Bước 6: Biên dịch và chạy chương trình
——————————————————————————————————
—————————–
Bước 1: Tạo tên Solution
Tôi đặt solution cho ví dụ này là: NetRemotingAndWindowsServices
Để đơn giản, tầng ProxyObject Tôi chỉ viết 1 class gọi là PrimeProxy, class này có
nhiệm vụ nhận vào 1 số nguyên từ tầng client, sau đó trả về dãy số nguyên tố từ 2
tới n và đồng thời cho biết client là người thứ mấy gọi yêu cầu lên server.
Cách tạo : Vào menu File/ New/ chọn Project hoặc nhấn tổ hợp phím Ctrl+Shift+N

Cửa sổ New Project sẽ hiển thị ra, bạn hãy chọn Blank Solution trong mục Visual
Studio Solutions

Trong ô Name: Nhập tên NetRemotingAndWindowsServices sau đó nhấn nút OK.


Bạn quan sát trong mục Solution Explorer sẽ xuất hiện tên Solution mà bạn vừa tạo

Bước 2: Tiến hành tạo 3 Project cho Solution: Tầng ProxyObject, tầng Server và
Client


Tầng ProxyObject: Trong tầng này bạn phải chọn là Class Library



Bấm chuột phải vào tên solution/ chọn Add / chọn New Project


Sau khi bạn chọn New Project thì cửa sổ Add New Project xuất hiện, tại cửa
sổ này bạn hãy chọn Class Libray



Trong ô Name: bạn gõ tên ProxyObject rồi click OK.


Tiếp theo bạn tạo tầng Server và Client, cách tạo 2 tầng này sẽ tương tự như
tầng ProxyObject, nhưng chọn là Windows Forms Application thay vì Class Library




Bạn tuần tự tạo xong các tầng, và quan sát Solution Explorer:

Ta có 3 Projects trong Solution NetRemotingAndWindowsServices
Bước 3: Tiến hành viết coding cho tầng ProxyObject



Đổi tên Class1 thành PrimeProxy và viết code như bên dưới:

using System;using


System.Collections.Generic;using System.Linq;using System.Text;
namespace ProxyObject{
public class PrimeProxy:MarshalByRefObject{//Biến lưu số lần client gọi hàm lấy danh
sách nguyên tố
private int m_RequestNumber = 0;
//Biến lưu tên Client hiện tại gọi hàm
private string m_strCurrentClient = “”;
//Biến lưu danh sách tên các client đã connect tới server
private List<string> m_listClient = new List<string>();
//hàm kiểm tra số nguyên tố
public bool isPrime(int k)
{
if (k < 2) return false;
for (int i = 2; i <= Math.Sqrt(k); i++)
if (k % 2 == 0) return false;
return true;
}
//hàm thiết lập client hiện tại connect tới server và
//lưu client vào danh sách đã kết nối
public void setConnectClient(string clientName)
{
m_strCurrentClient = clientName;



if (!m_listClient.Contains(clientName))
m_listClient.Add(clientName);
}
//Hàm trả về danh sách các số nguyên tố
public List<int> getListPrime(int n)
{
m_RequestNumber++;
List<int>lst=new List<int>();
for (int i = 2; i <= n; i++)
if (isPrime(i))
lst.Add(i);
return lst;
}
public int RequestNumber
{
get { return this.m_RequestNumber;}
}
public string CurrentClient
{
get { return this.m_strCurrentClient; }
}
public List<string> ListClient


{
get { return this.m_listClient; }
}
}
}


Bước 4: Tiến hành viết coding cho tầng Server
Đổi class Form1.cs thành frmServer.cs và thiết kế giao diện như hình bên dưới:

Control

Tên Control

Mô tả

TextBox

txtPort

Dùng để nhập Port
server

TextBox

txtStatus

Để hiện thị trạng thái
Server

RadioButton

radSingleton

Singleton

RadioButton


radSingleCall

SingleCall

Button

btnStart

Khởi động


Button

btnStop

Tắt

Sau khi thiết kế xong, để tiến hành Coding cho tầng Server thì bạn phải tham chiếu
như hướng dẫn bên dưới:

Tầng Server phải tham chiếu tới tầng ProxyObject và thư
viện System.Runtime.Remoting
Tham chiếu tới ProxyObject: Bấm chuột phải vào References / Add Reference…

Cửa sổ Add Reference hiển lên, chọn ProxyObject rồi nhấn OK

Tương tự khi Add tham chiếu tới thư viện System.Runtime.Remoting, trường hợp
này bạn chọn tab .NET thay vì tab Project.



Trong tab .NET bạn chọn System.Runtime.Remoting rồi nhấn OK
Sau đó bạn quan sát tầng Server, nếu như nó như hình bên dưới là đã thành công:



Bây giờ ta tiến hành viết code cho tầng Server, xem coding:

using System;using System.Collections.Generic;using
System.ComponentModel;


using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using ProxyObject;
namespace TangServer
{
public partial class frmServer : Form
{
private TcpChannel tcpChannel = null;
private int port = 8998;
private Type type;
private WellKnownObjectMode wellKnownMode;
private string objURI;

public frmServer()
{
InitializeComponent();
}


private void btnStart_Click(object sender, EventArgs e)
{
try
{
btnStop.PerformClick();
port = Int32.Parse(txtPort.Text);
//tạo kênh truyền dữ liệu
tcpChannel = new TcpChannel(port);
ChannelServices.RegisterChannel(tcpChannel, false);
//đăng ký remote object với Remoting framework
type = typeof(PrimeProxy);
objURI = “PRIME_URI”;
if (radSingleTon.Checked == true)
wellKnownMode = WellKnownObjectMode.Singleton;
else
wellKnownMode = WellKnownObjectMode.SingleCall;
RemotingConfiguration.RegisterWellKnownServiceType
(type, objURI, wellKnownMode);
txtStatus.Text = “khởi động server tại por ” + port.ToString() + ” lúc ”
+ DateTime.Now.ToString();
}
catch (Exception ex)



{
MessageBox.Show(“Lỗi”, ex.Message);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (ChannelServices.GetChannel(“tcp”) != null)
{
ChannelServices.UnregisterChannel(tcpChannel);
txtStatus.Text = “tắt server tại port ” + port.ToString() + ” lúc ” +
DateTime.Now.ToString();
}
}
}
}

Bước 5: Tiến hành viết code cho Tầng Client
Đổi class Form1.cs thành frmClient.cs và thiết kế giao diện như hình bên dưới:


Control

Tên Control

Mô tả

TextBox

txtIP


Địa chỉ server: tên hoặc IP

TextBox

txtPort

Để nhập Port kết nối

TextBox

txtClient

Tên client sử dụng : Tèo

TextBox

txtN

Nhập N để lấy dãy nguyên tố

Button

btnConnect

Bắt đầu kết nối tới server

Button

btnGetResult


Lấy kết quả từ server

ListBox

lstbListPrime

ListBox lưu dãy nguyên tố

ListBox

lstbListClient

ListBox lưu danh sách Client


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×