Silverlight 3.0 Network Communication

Source: Internet
Author: User
Tags getstream

Silverlight supports the use of HTTP/HTTPS (system. net. webClient) and socket (system. net. sockets). But for security reasons, strict security policies are set for these network accesses.

1. HTTP/HTTPS Access Policy

(1) Always allow calls in the same domain. The same domain indicates that the call must use the same subdomain, protocol, and port. This is for security reasons and prevents cross-domain forgery.

(2) Silverlight supports accessing website services that contain cross-origin policy files. During cross-origin access, Silverlight application first searches for the Silverlight cross-origin policy file (clientaccesspolicy. XML) in the root path of the target Web service ). If no (404 Not found) is found or other errors occur, the flash Cross-Domain Policy file (crossdomain. XML) will continue to be searched at the root path ).

Clientaccesspolicy. xml

<? XML version = "1.0" encoding = "UTF-8"?>
<Access-Policy>
<Cross-domain-access>
<Policy>
<Allow-from>
<Domain uri = "*"/>
</Allow-from>
<Grant-to>
<Resource Path = "/" include-subpaths = "true"/>
</Grant-to>
</Policy>
</Cross-Domain-access>
</Access-Policy>

(3) All communications are asynchronous.

(4) Only get and post predicates are supported.

(5) supports most standard request headers and all custom request headers (must be headers allowed in the Cross-origin policy file ).

<? XML version = "1.0" encoding = "UTF-8"?>
<Access-Policy>
<Cross-domain-access>
<Policy>
<Allow-from http-request-headers = "soapaction, X-custom-header">
<Domain uri = "*"/>
</Allow-from>
<Grant-to>
<Resource Path = "/services/" include-subpaths = "true"/>
</Grant-to>
</Policy>
</Cross-Domain-access>
</Access-Policy>

(6) Only "200 OK" and "404 Not Found" status codes are available.

We tried to use WebClient to access a cross-origin website.

Private void button_click (Object sender, routedeventargs E)
{
VaR client = new WebClient ();

Client. downloadstringcompleted + = (S, ex) =>
{
This. textblock1.text = ex. Error! = NULL? Ex. Error. tostring (): Ex. result;
};

Client. downloadstringasync (New uri ("http: // localhost: 8081/", urikind. Absolute ));
}

When the target website does not provide a policy file, you will see the following error message.

After the clientaccesspolicy. XML is placed in the root path, the access is normal.

2. Sockets Access Policy

To create a socket server that is connected to the Silverlight application, you must comply with the following security policies.

(1) Listen to port 943 and provide the policy file (clientaccesspolicy. XML) for the Silverlight application ).

(2) The Service port range of the socket server must be between 4502 and 4534. This is the port range allowed by the Silverlight application socket connection. Otherwise, the connection fails.

Let's write a simple time server for demonstration.

Server Cui

Class Program
{
Static void main (string [] ARGs)
{
Accesspolicyserver ();
Timeserver ();

Console. writeline ("press any key to exit ...");
Console. readkey (true );
Environment. Exit (0 );
}

/// <Summary>
/// Creation time server thread
/// </Summary>
Private Static void timeserver ()
{
New thread () =>
{
// Listen to port 4502
VaR Server = new tcplistener (IPaddress. parse ("127.0.0.1"), 4502 );
Server. Start ();

While (true)
{
VaR client = server. accepttcpclient ();
VaR stream = client. getstream ();

// Current sending time
VaR send = encoding. utf8.getbytes (datetime. Now. tostring ());
Stream. Write (send, 0, send. Length );

Client. Close ();
}
}). Start ();
}

/// <Summary>
/// Create a policy file server thread
/// </Summary>
Private Static void accesspolicyserver ()
{
New thread () =>
{
// Listen to port 943
VaR Server = new tcplistener (IPaddress. parse ("127.0.0.1"), 943 );
Server. Start ();

While (true)
{
VaR client = server. accepttcpclient ();
VaR stream = client. getstream ();

// Read the message sent by the client. If the request string does not match, it is disconnected.
VaR buffer = new byte [1024];
VaR Len = stream. Read (buffer, 0, buffer. Length );

VaR rece = encoding. utf8.getstring (buffer, 0, Len );
If (string. Compare (RECE, "<policy-file-Request/>", true )! = 0)
{
Client. Close ();
Break;
}

Console. writeline (RECE );

// Send policy file content
VaR send = encoding. utf8.getbytes (@"
<? XML version = "" 1.0 "" encoding = "" UTF-8 ""?>
<Access-Policy>
<Cross-domain-access>
<Policy>
<Allow-from>
<Domain uri = "*" "/>
</Allow-from>
<Grant-to>
<Socket-resource Port = "" 4502-4534 "" protocol = "" TCP "/>
</Grant-to>
</Policy>
</Cross-Domain-access>
</Access-Policy> ");

Stream. Write (send, 0, send. Length );

Client. Close ();
}
}). Start ();
}
}

Client Silverlight xap

Private void button_click (Object sender, routedeventargs E)
{
// Create a socket
VaR client = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );

// Create a waiting handle
VaR wait = new manualresetevent (true );

// Create connection Parameters
VaR ARGs = new socketasynceventargs ();
Args. remoteendpoint = new dnsendpoint ("127.0.0.1", 4502 );

// Subscribe to and process events
Args. Completed + = (S, ex) =>
{
If (ex. lastoperation = socketasyncoperation. Connect)
{
// When the connection is complete, set the buffer.
VaR buffer = new byte [1024];
Ex. setbuffer (buffer, 0, buffer. Length );

// Receives server data
Client. receiveasync (Ex );
}
Else if (ex. lastoperation = socketasyncoperation. Receive)
{
// If the received information is correct, the content sent by the server is displayed; otherwise, the error message is displayed.
If (ex. socketerror = socketerror. Success)
{
This. Dispatcher. begininvoke () =>
{
This. textblock1.text = encoding. utf8.getstring (ex. buffer, 0, Ex. bytestransferred );
});
}
Else
{
This. Dispatcher. begininvoke () =>
{
This. textblock1.text = ex. socketerror. tostring ();
});
}

Wait. Set ();
}
};

// Connect to the server
Client. connectasync (ARGs );

// Wait Until processing ends
Wait. waitone ();
}

If you do not start the Server policy file service or the port is not 943, you will get an accessdenied error on the client.

Of course, if the server listening port is no longer allowed within the range (4502-4534), this error will also be triggered.

[Reprinted from http://www.rainsts.net /]

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.