using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Net.Sockets; using System.Net; using System.Threading; namespace SoketServer { public partial class Form1 : Form { delegate void HanderVoid(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //监听策略请求和发送策略请求方法 建立一个子线程,用于创建Socket来监听策略请求和发送。 ThreadStart pcts = new ThreadStart(PolicyThread); Thread policythread = new Thread(pcts); policythread.Start(); //建立一个子线程,用于创建Socket来监听信息请求和发送。 ThreadStart infots = new ThreadStart(InfoThread); Thread infothread = new Thread(infots); infothread.Start(); } void PolicyThread() { //创建一个Socket用来监听943(固定的)端口的策略请求 Socket policy = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); policy.Bind(new IPEndPoint(IPAddress.Any, 943)); policy.Listen(10); //无限循环监听 while (true) { if (policy.Blocking)//如果Socket是阻止模式的(这个东西实际上可以用不) { //创建Socket,用来获取监听Socket的第一个Socket链接 Socket _policy = policy.Accept(); //定义一个字符串,该字符串与Silverlight发送过来的请求字符串一样。 string policyRequestString = "<policy-file-request/>"; //定义一个字节数组 byte[] b = new byte[policyRequestString.Length]; //将客户端发送过来,服务器接收到的字节数组存入b中 _policy.Receive(b); //将接收到的字节数组转换成字符串 string requeststring = System.Text.Encoding.UTF8.GetString(b, 0, b.Length); //显示客户端发送的字符串 Console.WriteLine(requeststring); //比对客户端发送过来的字符串是否和之前定义的额定好的策略请求字符串相同,如果相同,说明该请求是一个策略请求。 if (requeststring == policyRequestString) { //如果客户端发送的是一个策略请求,服务器发送策略文件到客户端 SendPolicy(_policy); Console.WriteLine("Policy File have sended"); //关闭当前连接Socket _policy.Close(); } else// 否则,显示错误 { Console.WriteLine("not a sure request string!"); } } } } //监听信息请求和发送信息方法 void InfoThread() { //创建一个Socket用于监听4502端口,获取接收客户端发送过来的信息 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IPAddress.Any, 4502)); socket.Listen(10); //无线循环监听 while (true) { //创建Socket,用来获取监听Socket的第一个Socket链接 Socket _socket = socket.Accept(); //创建一个空字节数组 byte[] b2 = new byte[1024]; //将接受到的字节数组存入到之前定义的b2字节数组中。 _socket.Receive(b2); //显示接收到的信息 // Console.WriteLine(Encoding.UTF8.GetString(b2)); // f.richTextBox1.AppendText(Encoding.UTF8.GetString(b2)); this.Invoke(new HanderVoid(delegate { this.richTextBox1.AppendText(Encoding.UTF8.GetString(b2)); })); //发回一个信息给客户端,该信息是字节数组,所以我们将信息字符串转换成字节数组 _socket.Send(Encoding.UTF8.GetBytes("This Send Over!!")); //关闭当前Socket连接 _socket.Close(); } } //发送策略文件的方法 //参数是传递进来的Socket连接 void SendPolicy(Socket socket) { //创建一个文件流,该文件留指定代开一个策略文件,至于策略文件的格式,MS的Silverlight有详细说明和配置方法 using (FileStream fs = new FileStream(@"p.txt", FileMode.Open)) { int length = (int)fs.Length; byte[] bytes = new byte[length]; //将策略文件流读到上面定义的字节数组中 fs.Read(bytes, 0, length); socket.Send(bytes); } } //监听策略请求和发送策略请求方法 } }