Sie sind auf Seite 1von 74

HO CHI MINH UNIVERSITY OF INDUSTRY

.NET
Remoting
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com

HO CHI MINH UNIVERSITY OF INDUSTRY

Net Remoting Definition:


Application which is located in another application domain or process can communicate with another by using .Net Remoting. Net Remoting allows processes to share the objects. It can call the method and can access the properties of an objects that are:
Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

You known Application Domain ?:


Application domain is the collection of classes, which isolate these from other applications. The application in one application domain could not access the application in other application domain (without using Remoting)

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.

Non Remotable Object

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

[Serializable] Class Foo { . . . }


Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

ASP.NET Web services (WS) vs .NET Remoting (NR)


See next slide

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.

HO CHI MINH UNIVERSITY OF INDUSTRY

.Net Remoting components


A remotable object. A host application. listen to requests for the hosted remotable object. A client application. requests for the remotable object.

Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com

How Does .NET Remoting Works?


In the client create a new remotable object =>creates a proxy object When client call method => call method on proxy=> server=> return to proxy => client

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

Server-Activated Objetcs (SAO) Client-Activated Objects (CAO)


Client-Activated Object: Server side object creation is handled by client application. An instance of object is created, when the client calls the new operator. Server-Activated Object: The object is created, when the client actually invoke a method on proxy. Single Call (stateless) This object handles one and only one request coming from client. Singleton This can be used to retain the state across multiple method calls.

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

Terms using in .Net Remoting Channel

Formatters

Author: Trn Duy Thanh Phone : 0987773061- Email: tranduythanh@hui.edu.vn Blog: http://duythanhcse.wordpress.com

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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.

HO CHI MINH UNIVERSITY OF INDUSTRY

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

Now How Remoting works?


Build Remote Object Build Host/Server application Build client application Create a new instance of remote object by using new While you do this, Remoting system creates the proxy object of Remotable object Remoting system receives that call and routes it to the server It then processes the request and return the result to the proxy, which intern return it to the client application.

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

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

HO CHI MINH UNIVERSITY OF INDUSTRY

2 Examples TcpChannel & HttpChannel

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)

See next slide.

Create TcpChannelRemoting solution:

Choose Visual Studio Solutions Type name: TcpChannelRemoting

Now, I add a ProxyObject class Library project into this solution.

Right click on solution / add / New Project

Choose Class Library Enter name: ProxyObject then click Ok button

And then add new class : MyProxy

Enter name: MyProxy.cs and click Add button

Inherit MarshalByRefObject as below:


using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace ProxyObject { public class MyProxy:MarshalByRefObject { } }

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 string GetInfor()


Return current name, number of request and all name client request in 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; } }

Create ServerTier Winform application project


Similar create ProxyObject project, but in this case, you choose Windows forms Application

You create UI as design


Control TextBox Name txtServerName Text Localhost

TextBox RadioButton
RadioButton Button Button Label

txtPort radSingleCall
radSingleTon btnStart btnStop lblStatus

9999 SingleCall
SingleTon Start Server Stop Server Status

Add Reference ProxyObject


-Right click on References/ Add reference

Add Reference System.Runtim.Remoting


Right click References/ Add Reference

OK!!!

Coding ServerTier: Using


using using using using System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; ProxyObject;

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 StopServer() { if (ChannelServices.GetChannel("tcp") != null) { ChannelServices.UnregisterChannel(tcpChannel); lblStatus.Text = "Server is Stopped!"; } }

ChannelServices.GetChannel("tcp") Check Channel is available


ChannelServices.UnregisterChannel(tcpChannel) Unregister channel

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

Control TextBox TextBox TextBox Label

Name txtServerName txtPort txtName lblSatus

Text Localhost 9999 Enter name client Status connect

Button
Button RichTextBox

btnGetInfor
btnConnect richInfor

Get Infor
Connect Get infor from server

Add Reference to ProxyObject & System.Runtime.Remoting as the same ServerTier

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 =

"tcp://" + s+ ":" + p+ "/MYPROXY_URI";


RemotingConfiguration.RegisterWellKnownClientType (typeof(MyProxy), url); lblStatus.Text = "Connected!"; }

MYPROXY_URI is defined from server

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

Choose Batch Build from menu Build

Checked all and then click Rebuild

Run ClientTier.exe

Also, We open ServerTier release folder to run ServerTier.exe

Whats problem with SingleCall???

Summary: SingleTon SingleCall RegisterChannel RegisterWellKnownServiceType RegisterWellKnownClientType And

HO CHI MINH UNIVERSITY OF INDUSTRY

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

Create ProxyObject, it has ChatInformation class


public class ChatInformation:MarshalByRefObject { private ArrayList clients = new ArrayList(); private string chatSession = ""; public void AddClient(string name) { if (name != null) { lock (clients) { clients.Add(name); } } }

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

using using using using

ProxyObject; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Http;

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

richHistory History chat

We use multi Threading to code Client Chat

using using using using using

ProxyObject; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Http; System.Threading;

Create Member variables:


private ChatInformation chatInfor; private string userName = ""; private Thread threadChat;

Next slide to see detail coding

Write code for Login button


private void btnLogin_Click (object sender, EventArgs e) { string URL = "http://" + txtServer.Text + ":" + txtPort.Text + "/CHATCHAT"; RemotingConfiguration.RegisterWellKnownClientType (typeof(ChatInformation), URL); chatInfor = new ChatInformation(); userName = txtName.Text; chatInfor.AddClient(userName); threadChat = new Thread(new ThreadStart(PollServer)); threadChat.Start(); }

See PollServer method in the next slide

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

Das könnte Ihnen auch gefallen