我使用从文档中获取的示例代码:所有代码都包含在SocketExample.as中,也就是DocumentClass。
package {
import flash.display.Sprite;
public class SocketExample extends Sprite {
public function SocketExample() {
var socket:CustomSocket = new CustomSocket("127.0.0.1", 5000);
}
}
}
import flash.errors.*;
import flash.events.*;
import flash.net.Socket;
class CustomSocket extends Socket {
private var response:String;
public var txt:TextField;
public function CustomSocket(host:String = null, port:uint = 0) {
super();
configureListeners();
if (host && port) {
super.connect(host, port);
}
}
private function configureListeners():void {
addEventListener(Event.CLOSE, closeHandler);
addEventListener(Event.CONNECT, connectHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
private function writeln(str:String):void {
str += "\n";
try {
writeUTFBytes(str);
}
catch(e:IOError) {
trace(e);
}
}
private function sendRequest():void {
trace("sendRequest");
response = "";
writeln("GET /");
flush();
}
private function readResponse():void {
var str:String = readUTFBytes(bytesAvailable);
response += str;
}
private function closeHandler(event:Event):void {
trace("closeHandler: " + event);
trace(response.toString());
}
private function connectHandler(event:Event):void {
trace("connectHandler: " + event);
sendRequest();
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function socketDataHandler(event:ProgressEvent):void {
trace("socketDataHandler: " + event);
readResponse();
}
public function returnResponse(){
return response.toString();
}
}
在套接字关闭时,closeHandler被调用。如何在舞台上将响应的值写入文本字段?我尝试从CustomSocket closeHandler发送一个自定义事件,但是,即使我正确地向SocketExample的构造函数添加了一个侦听器,我也没有收到任何事件。我该怎么办?
答案 0 :(得分:0)
您似乎已经添加了一个公共txt
字段,用于存储对文本字段的引用。如何在SocketExample
课程中创建文本字段,将其添加到舞台,然后设置socket.txt = yourTextField
。然后,您可以直接在txt
中使用closeHandler
。