Beruflich Dokumente
Kultur Dokumente
.NET
Remoting
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Hosted in different application domain with in the same process or Different process executing on same computer or Different computers connected by LAN or Different computer distributed over world wide
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Modern applications are no longer stand-alone applications. - Provides a solution for communication between application domains .NET Remoting:
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
2 Object type
Remotable Object It can be accessed outside its application domain. CLR objects cannot, by default, be used outside their AppDomain - No way to copy them - No way to reference them Exception occurs when you try to pass an object reference to a different domain SO: It can not be accessed outside its own application domain.
Remotable Object:
Can request that instances of a class be accessible outside original AppDomain Client get a copy of the object Client get a reference (proxy) to the original object When an object is Remotable? The object should inherit the class
System.MarshalByRefObject
Two Types of Remotable Objects are there Marshal by Value Marshal by Reference *More detail later
Object Serialization:
Conversion of an object (instance) into a data stream of bytes, Serialization is a method of persisting objects for storage in a database, to various media, or during marshalingthe process of moving an object to a new application domain, context, process, or system. Serialization is performed by the Common Language Runtime (CLR).
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Serializable objects:
When runtime can make a copy of the object, an object can marshal-by-value to other AppDomains Add SerializableAttribute Or implement the ISerializable interface
MarshalByRef objects:
When the object's class derives, directly or indirectly, from MarshalByRefObject, the runtime creates a proxy to the object
[Serializable] class Foo : System.MarshalByRefObject { . . . }
Clients in foreign AppDomains receive proxy How does a client specify what proxy?
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Remoting in general :
Clients must connect to servers Server needs to publish an object I listen on this TCP channel and that HTTP channel I have a service called "MathService" When client connects to MathService using a supported channel, give the client [ a | this ] Calculator instance Clients need to specify the desired object Connect to the "MathService" on server "LightningFast" using protocol HTTP on port 80
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
1. WS: only be accessed over HTTP; NR various protocols like TCP, HTTP etc. 2. WS stateless environment, NR state management 3. WS more reliable than .NET Remoting. 4. WS are easy to create and use, NR are complex to be created. 5. WS across platforms, NR requires client to be built using .NET 6. WS support datatypes defined in the XSD type system while .NET remoting provides support for rich type system using binary communication.
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Proxy
To avoid conjunction in networking. It contains reference to all methods and properties of object. There are two type of proxy. Transparent proxy (There is no physical existence, Created by IISserver) Real Proxy (Physical Existence)
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Remoting makes an object in server available to code in client => marshalling 2 ways to marshal an object Marshal by value the server creates a copy of the object passes the copy to the client Marshal by reference the client creates a proxy for the object and then uses the proxy to access the object
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Marshal by reference
2 types
SAO - CAO
Server-Activated lifetime is controlled by server Use when there are clients sharing the same server object Its a one-to-many relationship between the server object and clients Singleton SingleCall Is called: WellKnow object Client-Activated Objects lifetime is controlled by the client Use when multiple server instances of the same kind need to be run on the server at the same time one-to-one relationship between each server object and its corresponding client
Client-activated objects
Client-activated objects. Each client gets an independent object for its use. Like the classic client-server model, clients can still share objects.
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Server-activated objects:
Obj 1
Singleton Singlecall
Obj A Obj 3 Obj 4 Obj n
Obj 2
Share
Share
Share
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Formatters
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Channel:
The medium through the which the messages would be transferred The remote objects are to communicate with one another and channels do this transport job of communication. The two existing channels HttpChannel and TCPChannel
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Channel:
HTTPChannel use SOAP Formatter to serialize messages into the XML format using SOAP protocol. Using SOAP method allows the client to call method on the remote object that might not be using .Net framework. TCPChannel use binaryFormatter to serialize message into binary stream.
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Channel:
We have to register at least one channel to use with the remoting infrastructure before being able to call the Remotable type from the client application. We can register a channel in one of two ways: By ChannelServices.RegisterChannel, or By using a configuration file. We have to choose a specific port for your channel to listen on. If we are not sure whether a port is available or not, use 0 (zero) When you configuring your channels port and the remoting system will choose an available port for you.
Formatters Change the data in an appropriate format that it can traverse through channels. There are two types of formatters Binary SOAP(Simple Object Access Protocol)
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Note
Remote object should inherit MarshalbyRefObject class. A client needs to obtain proxy, should activate remote Object by Calling CreateInstance, GetObject or by using new key word. Local object has to be passed as parameter when making remote calls. It should passed by value. This object must be serialized.
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Remoting clients
A clients wants to use a remote object Well-known objects exist at a URL Client obtains proxy using Activator.GetObject Client can also obtain proxy using new
Client activated object factory exists at a URL
Client requests factory to instantiate object and return a proxy to it using Activator.CreateInstance Client can also make same request using new
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Activator.GetObject
GetObject returns a proxy for the served at the specified location No network traffic until first method call! Proxy built on client from metadata Server activates object on first method call
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
ExamplesTcpChannel
-Name solution : TcpChannelRemoting It has 3 projects: 1) ProxyObject class Library project 2) ServerTier (Winform application) 3) ClientTier (Winform application)
Modify class MyProxy: Add new 2 attributes: m_strName which string type to store current name of client request m_arr which ArrayList type to store list name from client request public void MakeRequest(string s)
Use to set current name and add this name into m_arr
public class MyProxy:MarshalByRefObject { private string m_strName = ""; private ArrayList m_arr=new ArrayList(); public MyProxy(){ } public void MakeRequest(string s) { this.m_strName = s; this.m_arr.Add(s); } public string GetInfor() { string sInfor = "Hello "+this.m_strName +"\n"; sInfor += " You are client " + this.m_arr.Count + "\n"; sInfor += " ---List client request---\n "; for (int i = 0; i < this.m_arr.Count; i++){ sInfor += this.m_arr[i] + "\n"; } return sInfor; } }
TextBox RadioButton
RadioButton Button Button Label
txtPort radSingleCall
radSingleTon btnStart btnStop lblStatus
9999 SingleCall
SingleTon Start Server Stop Server Status
OK!!!
TcpChannel tcpChannel = null;//Member variable name private void btnStart_Click(object sender, EventArgs e) {//Event for button Start Server StartServer(); } private void btnStop_Click(object sender, EventArgs e) {//Event for button Stop Server StopServer(); }
private void StartServer() {StopServer();// Call Stop server int port = Int32.Parse(txtPort.Text);//Get Port //Create TcpChannel tcpChannel = new TcpChannel(port); //Get WellKnownObjectMode WellKnownObjectMode mode=radSingleTon.Checked ? WellKnownObjectMode.Singleton : WellKnownObjectMode.SingleCall; Type type=typeof(MyProxy);//Get type object //Register Channel ChannelServices.RegisterChannel(tcpChannel,false); //Register Remoting object to Remoting framework RemotingConfiguration.RegisterWellKnownServiceType (type, "MYPROXY_URI", mode); lblStatus.Text = "Server is Starting... +mode.ToString(); In client Tier, we will use MYPROXY_URI }
Create ClientTier
Similar create ServerTier
Button
Button RichTextBox
btnGetInfor
btnConnect richInfor
Get Infor
Connect Get infor from server
Coding ClientTier
using System.Runtime.Remoting; using ProxyObject;
MyProxy myproxy; private void btnConnect_Click (object sender, EventArgs e) { string s= txtServerName.Text;//Server name string p = txtPort.Text;//Port string url =
Before slide, we write code for button Connect, Now we code for button Get infor: private void btnGetInfor_Click (object sender, EventArgs e) { myproxy = new MyProxy(); myproxy.MakeRequest(txtName.Text); richInfor.Text = myproxy.GetInfor(); }
Final, now we Batch Build Solution and run .exe
Run ClientTier.exe
Examples HttpChannel
Make public Chatting Application
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com
Server Chat UI
Client Chat UI
public void RemoveClient(string name) { if (clients != null) { lock (clients) { clients.Remove(name); } } } public void AddText(string text) { if (text != null) { lock (chatSession) { chatSession += text; } } }
public ArrayList GetClients() { return clients; } public string ChatSession() { return chatSession; } }
Create ServerChatUI Project, you must add full reference as the same example1
Control TextBox TextBox Button Button Label Name txtServerName txtPort txtStart txtStop lblStatus Text Localhost 9999 Start Server Stop Server Status
HttpChannel httpChanel; private void btnStart_Click(object sender, EventArgs e) { //Create httpChannel with Port httpChanel = new HttpChannel(Int32.Parse(txtPort.Text)); //Register httpchannel ChannelServices.RegisterChannel(httpChanel, false); //Register remote object to remote framework RemotingConfiguration.RegisterWellKnownServiceType (typeof(ChatInformation), "CHATCHAT", WellKnownObjectMode.Singleton); lblStatus.Text= "Server is starting...."; } private void btnStop_Click(object sender, EventArgs e) { if (ChannelServices.GetChannel("http") != null) { ChannelServices.UnregisterChannel(httpChanel); lblStatus.Text = "Server is Stopped!"; } } CHATCHAT will be use in the client UI
Create ClientChatUI Project, you must add full reference as the same example1
Control TextBox Name txtServer Text Localhost
TextBox
TextBox RichTextBox RichTextBox ListBox Button Button Button Button
txtPort
txtName richChat listUser btnLogin btnSend btnClear btnLogout
9999
User name Enter chat List user login Login Send Chat Clear Chat Logout
int selectedIndex = 0; private void PollServer() { for (; ; ) {Thread.Sleep(1000); ArrayList clients = chatInfor.GetClients(); selectedIndex = listUser.SelectedIndex; listUser.Items.Clear(); for (int i = 0; i < clients.Count; i++) {listUser.Items.Add(clients[i].ToString()); } listUser.SelectedIndex = selectedIndex; string sessionText = chatInfor.ChatSession(); richHistory.Clear(); richHistory.Text = sessionText; } }
private void btnLogout_Click (object sender, EventArgs e) { chatInfor.RemoveClient(userName); listUser.Items.Clear(); listUser.Items.Add("No longer logged in..."); threadChat.Abort(); } private void btnClear_Click (object sender, EventArgs e) {richChat.Clear(); } private void btnSend_Click (object sender, EventArgs e) { chatInfor.AddText(userName +":\n"+richChat.Text+"\n\n"); }
END