Introduction to. Net remoting Programming

Source: Internet
Author: User
. Net remoting provides a powerful and efficient way to process remote objects ,. NET remote objects are very suitable for accessing resources through the network without the need to deal with the difficulties brought about by soap-based WebServices .. Net remoting is easier to use than Java's RMI, but it is more difficult to create a web service.

In this article Article . This article also includes a Substitute Object that ignores the database function, so that readers without a database can still use. Net remoting.

Step 1: create a shared library
Choose "file"> "new"> "project", create a C # library, name it resumeserverlibrary, and click "OK. This will create a "shared command set" for communication between our. NET remote client and the server ".

Positive is complete Code To skip the database access section, replace the resumeloader object with the following code:

Public class resumeloader: system. externalbyrefobject
{
Public resumeloader ()
{
System. Console. writeline ("New referance added! ");
}

Public resume getresumebyuserid (decimal userid)
{
Return New resume (1 );
}
}


Namespace is required by the object. Remember, if you get system. runtime. remoting. channels. the TCP namespace does not exist. Check whether the system is added as the code above. runtime. remoting. DLL reference.

Using system;
Using system. runtime;
Using system. Data. sqlclient;

The namespace we use for the object is dotnetremotetest. The following object is marshalbyrefobject. In this space, we create a reference and include server-side database operations to complete all the required work.

Namespace dotnetremotetest
{
Public class resumeloader: system. externalbyrefobject
{
Private sqlconnection dbconnection;

Public resumeloader ()
{
This. dbconnection = new system. Data. sqlclient. sqlconnection ();
This. dbconnection. connectionstring =
"Data Source = grimsaado2k; initial catalog = underground; Integrated Security = sspi; PERS" +
"Ist Security info = true; workstation id = grimsaado2k; packet size = 4096 ";
/* The specific connection string will be different, which is beyond the scope of this article. If you do not know how to create a database connection, use another version of this object. */
System. Console. writeline ("New referance added! ");
}

Public resume getresumebyuserid (decimal userid)
{
Resume resume = New resume ();
Try
{
Dbconnection. open ();
Sqlcommand cmd = new sqlcommand (
"Select resumeid, userid, title, body from resume as theresume where theresume. userid =" + userid + ""
, Dbconnection
);
Sqldatareader areader = cmd. executereader ();
If (areader. Read ())
{
Resume. resumeid = areader. getdecimal (0 );
Resume. userid = areader. getdecimal (1 );
Resume. Title = areader. getstring (2 );
Resume. Body = areader. getstring (3 );
}
Areader. Close ();
Dbconnection. Close ();
}
Catch (exception X) {resume. Title = "error:" + X ;}
Return resume;
}
}


Resume needs to be serializable so that it can be called remotely. NET remote object return type, because the object will be converted to the original data transmitted over the network, and then assembled into an object at the other end of the network.

This object is very simple. To make this article look simpler, the constructor even uses the default content to initialize some of the fields.

[Serializable]
Public class resume
{
Private decimal resumeid, userid;
Private string body, title;
Public resume (decimal resumeid)
{
This. resumeid = resumeid;
This. userid = 1;
This. Body = "this is the default body of the resume ";
This. Title = "this is the default title ";
}

Public decimal resumeid
{
Get {return resumeid ;}
Set {This. resumeid = value ;}
}
Public decimal userid
{
Get {return userid ;}
Set {This. userid = value ;}
}
Public String body
{
Get {return body ;}
Set
{
This. Body = value;
}
}
Public String title
{
Get {return title ;}
Set
{This. Title = value ;}
}

} // End of the resume object

} // Dotnetremotetest namespace ends


Compile the created project to obtain a DLL file and use it in other projects.

Step 2: Create a Server Object
There are several ways to create a server object. The most intuitive method is the following: in Visual Studio.. net, click "file"> "new"> "project", and select "command line application ". Program And name it resumesuperserver.

Most importantly, we need to add an application for the DLL file created in step 1 so that the application can run correctly. Choose "project"> "add reference", and click "Browse" to add a reference to the DLL file created in step 1.

To use the. NET remote function, You must select "project"> "add reference" to add a reference to the DLL file. In the. NET label, select system. runtime. remoting. dll and click "OK. Then, add a reference to system. runtime. remoting. dll as we did in step 1.

The following objects are quite simple and intuitive. I will explain each line in the three lines of code that are really related to. Net remoting.

Tcpserverchannel is. net remoting supports one of the two channel types, which will set the request from which the object we want to respond to, channelservices. registerchannel binds the port number to the TCP/IP stack in the operating system.

Tcpserverchannel channel = new tcpserverchannels (9932 );
Channelservices. registerchannel (Channel );

Another channel type that can be set is HTTP. You can simply use the httpserverchannel object in the system. runtime. remoting. channels. Http namespace. The difference between HTTP and TCP channels can be simply summarized as: if the application runs on the LAN, it is best to use the TCP channel because it has better performance than the HTTP channel; if an application runs on the internet, HTTP is the only option based on the firewall configuration. Remember that if the firewall software is used, the Firewall should be configured to allow TCP data traffic to pass through the port you selected for the object.

Remotingconfiguration. registerwellknownservicetype (typeof (resumeloader ),
"Resumeloader", wellknownobjectmode. singlecall );

This line of code sets some parameters in the service and binds the name of the target object to a remote object. The first parameter is the bound object, the second parameter is the string of the remote object name in the TCP or HTTP channel. The third parameter tells the container how to process the object when a request to the object is sent. Although wellknownobjectmode. Single uses an object instance for all callers, it generates an instance of this object for each customer.

The complete object code is as follows:

Using system;
Using system. runtime;
Using system. runtime. remoting;
Using system. runtime. remoting. channels;
Using system. runtime. remoting. channels. TCP;
Using system. Data. sqlclient;
Using dotnetremotetest;
Namespace resumeserverserver
{
Public class resumesuperserver
{
Public static void main (string [] ARGs)
{
Tcpserverchannel channel = new tcpserverchannels (9932 );
Channelservices. registerchannel (Channel );
Remotingconfiguration. registerwellknownservicetype (typeof (resumeloader ),
"Resumeloader", wellknownobjectmode. singlecall );
System. Console. writeline ("press any key ");
System. Console. Readline ();
}
}
}


Compile this program and pay attention to the location of the generated. EXE file.

Step 3: Create a remote client program
Resumeclinet is created for testing the resumesuperserver and objects created above. To create this project, click "file"> "CREATE"> "project" in sequence, and then select the project name that creates a console application type and is named resumeclient. As in step 2, we need to add references to the DLL file created in step 1 and system. runtime. remoting DLL.

The following code contains two lines that are particularly important for. Net remoting. The first line creates a tcp client channel, which is not bound to a port; the second line obtains a reference to the remote resumeloader object. The activator. GetObject method returns a value of the object type, which is then assigned to resumeloader. The parameters we pass to it are very similar to the parameters passed to remotingconfiguration in the server project. The first parameter is of the object type, and the second parameter is the URI of the remote object.

Channelservices. registerchannel (New tcpclientchannel ());
Resumeloader loader = (resumeloader) activator. GetObject (
Typeof (resumeloader), "TCP: // localhost: 9932/resumeloader ");
All the resumeclient code is as follows:
Using system;
Using system. runtime. remoting;
Using system. runtime. remoting. channels;
Using system. runtime. remoting. channels. TCP;
Using dotnetremotetest;

Namespace resumeclient
{

Public class resumeclient
{

Public static void main (string [] ARGs)
{
Channelservices. registerchannel (New tcpclientchannel ());
Resumeloader loader = (resumeloader) activator. GetObject (
Typeof (resumeserver), "TCP: // localhost: 9932/resumeloader ");

If (rs = NULL)
{Console. writeline ("unable to get remote referance ");}
Else
{
Resume resume = loader. getresumebyuserid (1 );
Console. writeline ("resumeid:" + resume. resumeid );
Console. writeline ("userid:" + resume. userid );
Console. writeline ("title:" + resume. Title );
Console. writeline ("Body:" + resume. Body );
}
Console. Readline (); // do not close the window until the result is displayed.
} // End of main method
} // End of resumeclient object
} // End of resumeclientnamespace


Test
Create a table with the following structure in the database:

Table Name-resume
Resumeid, numeric (autonumber)
Userid, numeric
Title, char (30)
Body, text

Double-click the server.exe created in step 2, and double-click the client Executable File Created in step 3. If everything is normal, we should be able to see the record line with the resumeid value of 1 in the database.

In short,. Net remoting is easy to use and provides an excellent way to process resources on a LAN or even on the Internet.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.