当使用flash.net.Socket类连接到远程服务器时,我遇到了一个奇怪的情况。在Flash Professional层的代码空间中直接编写套接字时,可以建立持久连接,并且仅为ONCE建立连接。但是,如果我将该连接逻辑包装到一个类中,那么类实例就会不断创建像疯狂一样的新套接字。
所以这是运行socket standalone时的代码:
var host:String = 'xx.xx.xx.xx';
var port:Number = 123456;
trace("host:"+host);
trace("port:"+port);
if (true){
var socket:Socket = new Socket(host, port);
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
function onConnect(e:Event):void {
trace("Connected to socket...");
Log.info("Connected to socket...");
}
function onClose(e:Event):void {
// Security error is thrown if this line is excluded
trace("Closing socket...");
Log.info("Closing socket...");
socket.close();
}
function onError(e:IOErrorEvent):void {
trace("IO Error: "+e);
Log.info("IO Error: "+e);
}
function onSecError(e:SecurityErrorEvent):void {
trace("Security Error: "+e);
Log.info("Security Error: "+e);
}
function onResponse(e:ProgressEvent):void {
if (socket.bytesAvailable>0) {
var res:String = socket.readUTFBytes(socket.bytesAvailable);
trace(res);
Log.info(res);
}
}
}
以下是类中带套接字的代码:
package com.example {
import flash.net.Socket;
import flash.events.*;
import com.example.utils.Log;
public class MockSession {
private var socket:Socket;
public function MockSession(host:String,port:Number):void{
socket = new Socket(host,port);
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
}
private function onConnect(e:Event):void {
trace("Connected to socket...");
Log.info("Connected to socket...");
}
private function onClose(e:Event):void {
// Security error is thrown if this line is excluded
trace("Closing socket...");
Log.info("Closing socket...");
socket.close();
}
private function onError(e:IOErrorEvent):void {
trace("IO Error: "+e);
Log.info("IO Error: "+e);
}
private function onSecError(e:SecurityErrorEvent):void {
trace("Security Error: "+e);
Log.info("Security Error: "+e);
}
private function onResponse(e:ProgressEvent):void {
if (socket.bytesAvailable>0) {
var res:String = socket.readUTFBytes(socket.bytesAvailable);
trace(res);
Log.info(res);
}
}
}
}
它是如何在Flash代码层中运行的:
import com.example.MockSession;
var session2:MockSession = new MockSession('xx.xx.xx.xx', 123456);
这产生了一堆" socket连接" MSG ...
Connected to socket...
Connected to socket...
Connected to socket...
Connected to socket...
Connected to socket...
Connected to socket...
Connected to socket...
Connected to socket...
......
我无法弄清楚如何使用课程有所不同。任何人都可以帮助我吗?
答案 0 :(得分:1)
你的代码似乎没问题。 但要更加确定:
最后,您可以在MockSession类中添加一个单例条目,以确保始终只有一个实例(当然,如果您不打算一次打开多个套接字)。