我有一个Groovy服务器和Flex客户端。当我尝试从Flex连接到Groovy应用程序时,我会发现<policy-file-request/>
消息。然后我发送一些策略XML响应并尝试向服务器发送一些东西。但是在Groovy方面没有收到任何东西,我什么也没得到。几秒钟后,我在Flex应用程序端获得SecurityException
。
Groovy服务器代码:
import java.util.Scanner
class server
{
public static handleConnection(client)
{
PrintWriter socketwriter = new PrintWriter(client.getOutputStream())
Scanner socketreader = new Scanner(client.getInputStream())
while (socketreader.hasNext())
{
String s = socketreader.nextLine()
println s
if (s =~ /<policy-file-request\s*\/>/)
{
socketwriter.print("<?xml version=\"1.0\"?><!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\"><cross-domain-policy><site-control permitted-cross-domain-policies=\"master-only\" /><allow-access-from domain=\"*\" to-ports=\"2900-2910\" /></cross-domain-policy>\n\0\n")
socketwriter.flush()
socketwriter.close()
client.close()
println "Policy File sent."
return
}
}
socketwriter.print("Connection: Done.\n")
socketwriter.flush()
socketwriter.close()
socketreader.close()
}
static main(args)
{
ServerSocket serversocket
try
{
serversocket = new ServerSocket(2900)
println "Server is up and running"
while (true)
{
Socket client = serversocket.accept()
Thread.start {
server.handleConnection(client)
}
}
} catch (e)
{
e.printStackTrace()
} finally
{
serversocket.close()
}
}
}
Flex客户端代码:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import flash.net.Socket;
import flash.events.*;
import mx.controls.Alert;
private var socket : Socket;
private function connect() : void
{
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, ServerSecurityError);
socket.connect("localhost", 2900);
Alert.show("yay!");
}
private function ServerSecurityError(evt : Event) : void
{
Alert.show("security error")
}
private function onConnect(evt : Event) : void
{
Alert.show("Connected to server!");
}
private function onSocketData(evt : ProgressEvent) : void
{
var data : String = socket.readUTFBytes(socket.bytesAvailable);
Alert.show("Read: " + data);
}
private function send() : void
{
var msg : String = "Hello, World!";
socket.writeUTFBytes(msg);
socket.flush();
Alert.show("Sent: " + msg);
}
]]>
</mx:Script>
<mx:Button label="connect" click="connect()" x="10" y="10" />
<mx:Button label="send something" click="send()" x="10" y="40" />
</mx:Application>
所以,问题是:我应该如何连接以获得服务器和客户端之间的稳定通信?
答案 0 :(得分:2)
出现SecurityError
的原因如下(来自文档):
我们正在运行类似的设置(使用纯AS3前端),在我调用connect()
之前,我打电话给:
Security.loadPolicyFile( "xmlsocket://" + this.m_host + ":" + this.m_policyFilePort );
其中m_host
可以是“localhost”,m_policyFilePort
是您正在服务的任何端口。您可以在here或at the Socket files