package {
import flash.display.*;
import flash.net.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
public class CChat extends MovieClip {
var str_user:String = "未知";
/
var sendUrl:String = "send.php";
var recvUrl:String = "recv.php";
var timer:Timer;
public function CChat() {
this.send_btn.addEventListener(MouseEvent.CLICK, sendMessage);
timer = new Timer(5000, 0);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
loadMessages();
}
public function setUserName(str:String):void {
str_user = str;
}
private function timerHandler(e:TimerEvent):void {
loadMessages();
}
public function setPosition(X:int, Y:int):void {
this.x = X;
this.y = Y;
}
private function loadMessages():void {
var randomTxt:String= "?rand="+Math.random();
var urlRequest:URLRequest = new URLRequest(recvUrl+randomTxt);
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, loadMessagesHandler);
urlLoader.load(urlRequest);
}
private function loadMessagesHandler(e:Event):void {
var loader:URLLoader = URLLoader(e.target);
var xml:XML = new XML(loader.data);
//清空数据
chat_list.htmlText = "";
for each (var item in xml..data) {
addMessage(item.name, item.message);
}
}
private function addMessage(user:String, msg:String):void {
chat_list.htmlText += user + ": " + msg + "\n";
}
private function sendMessageHandler(e:Event):void {
input_txt.text = "";
trace("发送成功.");
}
private function sendMessage(e:MouseEvent):void {
var variables:URLVariables = new URLVariables();
variables.user = str_user;
variables.msg = input_txt.text;
var urlRequest:URLRequest = new URLRequest(sendUrl);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = variables;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, sendMessageHandler);
urlLoader.load(urlRequest);
addMessage(str_user, input_txt.text);
}
}
}
界面如下:
创建一个.fla文件,,添加关键帧入上图,帧代码如下:
stop();
enter_btn.addEventListener(MouseEvent.CLICK, enterHandler);
function enterHandler(e:MouseEvent):void {
if (enter_txt.text!="") {
enter_btn.removeEventListener(MouseEvent.CLICK, enterHandler);
removeChild(enter_btn);
removeChild(enter_txt);
var chat:MovieClip = new CChat();
chat.setUserName(enter_txt.text);
addChild(chat);
}
}
创建影片剪辑元件,绑定CChat 类,界面如下:
数据库表如下: