简体   繁体   中英

Security Sandbox violation for socket connection using flex

import flash.events.*;
import flash.net.XMLSocket;
import flash.system.Security;

public class DotNetSocketExample {

    private var hostName:String = "170.21.8.0";
    private var port:uint =4000;
    private var socket:XMLSocket;


    public function DotNetSocketExample()
    {
        socket = new XMLSocket();
        configureListeners(socket);

       // Security.allowDomain("*");
       // Security.allowInsecureDomain("*");
        Security.loadPolicyFile("http://localhost/crossdomain.xml");
        socket.connect(hostName, port);
    }

    public function send(data:Object):void {
        socket.send(data);
    }

    public function disconnect():void {
        socket.close();
    }       

    private function configureListeners(dispatcher:IEventDispatcher):void {
        dispatcher.addEventListener(Event.CLOSE, closeHandler);
        dispatcher.addEventListener(Event.CONNECT, connectHandler);
        dispatcher.addEventListener(DataEvent.DATA, dataHandler);
        dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
        dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
    }

    private function closeHandler(event:Event):void {
        trace("closeHandler: " + event);
    }

    private function connectHandler(event:Event):void {
        trace("connectHandler: " + event);
    }

    private function dataHandler(event:DataEvent):void {
        trace("dataHandler: " + event);
    }

    private function ioErrorHandler(event:IOErrorEvent):void {
        trace("ioErrorHandler: " + event);
    }

    private function progressHandler(event:ProgressEvent):void {
        trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
    }

    private function securityErrorHandler(event:SecurityErrorEvent):void {
        trace("securityErrorHandler: " + event);
    }
}

}


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
    <![CDATA[

        private var sockExample:DotNetSocketExample = new DotNetSocketExample()

        private function send():void
        {
            sockExample.send(send_txt.text);                
        }

        private function disconnect():void
        {
            sockExample.disconnect();
        }

    ]]>
</mx:Script>

<mx:Panel width="468" height="116" layout="absolute" horizontalCenter="0" verticalCenter="0" backgroundColor="#EEEEEE" id="DotNetSocketConnectPanel" title="Dotnet Socket Connect Example">
    <mx:Button x="327" y="40" label="Disconnect" width="95" id="disconnect_btn" click="disconnect()"/>
    <mx:Button x="327" y="10" label="Send" width="95" id="send_btn" click="send()"/>
    <mx:TextInput x="21" y="10" width="298" id="send_txt" maxChars="100"/>
</mx:Panel>


using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TcpSock
{
    class TcpSock
    {
        int tcpIndx = 0;
        int tcpByte = 0;
        byte[] tcpRecv = new byte[1024];

        ////////////////////////////////////////
        public Socket tcpSock;
        ////////////////////////////////////////

        public int Recv(ref string tcpRead)
        {
            try
            {
                tcpByte = tcpSock.Available;
                if (tcpByte > tcpRecv.Length - tcpIndx)
                    tcpByte = tcpRecv.Length - tcpIndx;

                tcpByte = tcpSock.Receive(tcpRecv, tcpIndx, tcpByte,
                    SocketFlags.Partial);
                tcpRead = Encoding.ASCII.GetString
                    (tcpRecv, tcpIndx, tcpByte);
                tcpIndx += tcpByte;

            }
            catch (Exception ex)
            {
                //Error
            }
            return tcpRead.Length;
        }

        public int RecvLn(ref string tcpRead)
        {
            tcpRead = Encoding.ASCII.GetString
                (tcpRecv, 0, tcpIndx);
            tcpIndx = 0;
            return tcpRead.Length;
        }

        public int Send(string tcpWrite)
        {
            String POLICY_FILE = String.Empty;
            byte[] write = new byte[1024];
            write = Encoding.ASCII.GetBytes(tcpWrite);


            //if (tcpWrite.StartsWith("<policy-file-request/>"))
            //{

            //    POLICY_FILE = "<?xml version=\"1.0\" ?> \n" +
            //                     "<!DOCTYPE cross-domain-policy> \n " +
            //                     "<cross-domain-policy> \n" +
            //                     "<site-control permitted-cross-domain-policies=\"all\" /> \n" +
            //                     "<allow-access-from domain=\"*\" to-ports=\"*\" secure=\"true\" /> \n " +
            //                     "<allow-http-request-headers-from domain=\"*\" headers=\"*\" secure=\"false\" /> \n" +
            //                     "</cross-domain-policy>\n";


            //}
            return tcpSock.Send(write);
        }

        public int SendLn(string tcpWrite)
        {
            return tcpSock.Send(Encoding.ASCII.GetBytes(tcpWrite + "\r\n"));
        }
    }


    class Tcp
    {
        [STAThread]
        static void Main()
        {
            ////////////////////////////////////////////////////////////////////////////////////////////
            ///class IPHostEntry : Stores information about the Host and is required 
            ///for IPEndPoint.
            ///class IPEndPoint  : Stores information about the Host IP Address and 
            ///the Port number.
            ///class TcpSock     : Invokes the constructor and creates an instance.
            ///class ArrayList   : Stores a dynamic array of Client TcpSock objects.

            IPHostEntry Iphe = Dns.Resolve(Dns.GetHostName());
            IPEndPoint Ipep = new IPEndPoint(Iphe.AddressList[0], 4000);
            Socket Server = new Socket(Ipep.Address.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

            ////////////////////////////////////////////////////////////////////////////////////////////
            ///Initialize
            ///Capacity : Maximux number of clients able to connect.
            ///Blocking : Determines if the Server TcpSock will stop code execution 
            ///to receive data from the Client TcpSock.
            ///Bind     : Binds the Server TcpSock to the Host IP Address and the Port Number.
            ///Listen   : Begin listening to the Port; it is now ready to accept connections.

            ArrayList Client = new ArrayList();
            string rln = null;

            Client.Capacity = 256;
            Server.Blocking = false;
            Server.Bind(Ipep);
            Server.Listen(32);

            Console.WriteLine("{0}: listening to port {1}", Dns.GetHostName(),
                Ipep.Port);

            ////////////////////////////////////////////////////////////////////////////////////////////
            ///Main loop
            ///1. Poll the Server TcpSock; if true then accept the new connection.
            ///2. Poll the Client TcpSock; if true then receive data from Clients.

            while (true)
            {
                //Accept
                if (Server.Poll(0, SelectMode.SelectRead))
                {
                    int i = Client.Add(new TcpSock());
                    ((TcpSock)Client[i]).tcpSock = Server.Accept();
                    ((TcpSock)Client[i]).SendLn("Welcome.");
                    Console.WriteLine("Client {0} connected.", i);
                }

                for (int i = 0; i < Client.Count; i++)
                {
                    //check for incoming data
                    if (((TcpSock)Client[i]).tcpSock.Poll(0, SelectMode.SelectRead))
                    {
                        //receive incoming data
                        if (((TcpSock)Client[i]).Recv(ref rln) > 0)
                        {
                            //echo incoming data
                            ((TcpSock)Client[i]).Send(rln);

                            //check for new line
                            if (rln == "\r\n")
                            {
                                ///receive line
                                ((TcpSock)Client[i]).RecvLn(ref rln);

                                //send the line to all clients
                                for (int y = 0; y < Client.Count; y++)
                                    if (y != i)
                                        ((TcpSock)Client[y]).Send(i.ToString() + ": " + rln);

                                Console.Write("{0}: {1}", i, rln);
                            }
                        }
                        //recv returned <= 0; close the socket
                        else
                        {
                            ((TcpSock)Client[i]).tcpSock.Shutdown(SocketShutdown.Both);
                            ((TcpSock)Client[i]).tcpSock.Close();
                            Client.RemoveAt(i);
                            Console.WriteLine("Client {0} disconnected.", i);
                        }
                    }
                }
            }
        }
    }
}

I want to implement flex web application using Socket connection. But I am getting sand box violation error for remote sites in sample application . It is working fine in local.

Error:

Security Sandbox Violation 
Error: Request for resource at xmlsocket://170.21.8.0:4000 by requestor from http://localhost/Sample/DotNetSocketConnect.swf is denied due to lack of policy file permissions.

Try to Google crossdomain.xml
You need to put this file in the root of your server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM