Introduced
Silverlight 2.0Socket Communication. Develop a chat room for multiple people
Server side: Instantiate socket, bind, monitor, connect, receive data, send data
Client: Instantiate socket, specify service-side address, connect, receive data, send data
Example
1, Policy Service (the service that sends the policy file to the client)
ClientAccessPolicy.xml
<?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>
Main.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.Net.Sockets;
Using System.IO;
Using System.Net;
Namespace Policyserver
{
public partial class Main:form
{
Request information from client sockets to the policy file sent to the server
Private readonly string _policyrequeststring = "<policy-file-request/>";
Private Socket _listener; Socket for service-side listening
Private byte[] _policybuffer; Server-side policy file buffer
Private byte[] _requestbuffer; Buffer for request information sent by client socket
private int _received; Number of bytes of information received
private bool _flag = false; Sign bit. Whether the service side wants to process incoming connections
System.Threading.SynchronizationContext _synccontext;
Public Main ()
{
InitializeComponent ();
_flag = true;
Lblstatus.text = "Policyserver state: Start";
Lblstatus.forecolor = Color.green;
Start Policyserver
Startuppolicyserver ();
UI thread
_synccontext = System.Threading.SynchronizationContext.Current;
}
private void Btnstartup_click (object sender, EventArgs e)
{
_flag = true;
Lblstatus.text = "Policyserver state: Start";
Lblstatus.forecolor = Color.green;
}
private void Btnpause_click (object sender, EventArgs e)
{
_flag = false;
Lblstatus.text = "Policyserver state: Paused";
Lblstatus.forecolor = color.red;
}
/**////<summary>
Start Policyserver
</summary>
private void Startuppolicyserver ()
{
String policyFile = Path.Combine (Application.startuppath, "clientaccesspolicy.xml");
using (FileStream fs = new FileStream (PolicyFile, FileMode.Open, FileAccess.Read))
{
Writes the contents of a policy file to buffer
_policybuffer = new Byte[fs. Length];
Fs. Read (_policybuffer, 0, _policybuffer.length);
}
Initialize the socket, bind to the port, and then monitor the port
_listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
_listener. Bind (New IPEndPoint (Ipaddress.any, 943)); Socket request policy file uses port 943
_listener. Listen (100);
Start accepting incoming connections from clients
_listener. BeginAccept (New AsyncCallback (Onclientconnect), null);
}
private void Onclientconnect (IAsyncResult result)
{
if (!_flag)
{
The incoming connection is no longer processed if the policyserver is deactivated
_listener. BeginAccept (New AsyncCallback (Onclientconnect), null);
Return
}
Socket client; The socket that the client sent over
Try
{
Completes this asynchronous operation that accepts incoming connections from the client and returns the socket to which the client is connected
Client = _listener. Endaccept (result);
}
catch (SocketException)
{
Return
}
_requestbuffer = new Byte[_policyrequeststring.length];
_received = 0;
Try
{
Start receiving incoming data from the client
Client. BeginReceive (_requestbuffer, 0, _policyrequeststring.length, Socketflags.none, New AsyncCallback (OnReceive), client) ;
}
catch (SocketException)
{
Socket error closes client socket
Client. Close ();
}
Continue to accept incoming connections from clients
_listener. BeginAccept (New AsyncCallback (Onclientconnect), null);
}
private void OnReceive (IAsyncResult result)
{
Socket client = result. AsyncState as Socket;
Try
{
Completes this asynchronous operation to receive data and calculates the number of bytes of the cumulative received data
_received = client. EndReceive (result);
if (_received < _policyrequeststring.length)
{
Does not receive full data, continue to start receiving
Client. BeginReceive (_requestbuffer, _received, _policyrequeststring.length-_received, Socketflags.none, New AsyncCallback ( onreceive), client);
Return
}
Converts the received data to a string
String request = System.Text.Encoding.UTF8.GetString (_requestbuffer, 0, _received);
if (StringComparer.InvariantCultureIgnoreCase.Compare (Request, _policyrequeststring)!= 0)
{
If the received data is not "<policy-file-request/>", close the client socket
Client. Close ();
Return
}
Start sending the contents of a policy file to the client
Client. BeginSend (_policybuffer, 0, _policybuffer.length, Socketflags.none, New AsyncCallback (OnSend), client);
}
catch (SocketException)
{
Socket error closes client socket
Client. Close ();
}
}
private void OnSend (IAsyncResult result)
{
Socket client = result. AsyncState as Socket;
Try
{
Completes this asynchronous operation that sends the information to the client
Client. Endsend (result);
Gets the IP address and port number of the client, and displays
_synccontext.post (resultcallback, client. Localendpoint.tostring ());
}
Finally
{
Close Client Socket
Client. Close ();
}
}
void Resultcallback (object result)
{
The IP address and port number of the output client
Txtmsg.text + = result. ToString () + "\ r \ n";
}
}
}