问题
In FMS i want to use Shared objects to send messages in a chat application because its in real time. My question is...How do you use Shared Objects to send messages back and forth to users in a live chat application? Would this require Server-side scripting, client or both?
回答1:
You'll only need to write some code on the server-side for specific functionalities, such as security features (if not all the users can send messages for example).
On the client side, you need to:
- connect to the server;
- get the shared object from the server. If it does not exist when you ask for it, it will be created;
- add a listener on it for
SyncEvent
.
From there, every time a client will add, update or delete a property of the sharedObject using the setProperty()
method, all the connected clients will receive a SyncEvent
.
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.SyncEvent;
import flash.net.NetConnection;
import flash.net.SharedObject;
public class Chat extends EventDispatcher
{
public var messages:Array;
private var connection:NetConnection;
private var chat_so:SharedObject;
public function Chat()
{
super();
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
messages = [];
}
public function connect(uri:String):void
{
connection.connect(uri);
}
public function addMessage(value:String):void
{
chat_so.setProperty(messages.length.toString(), value);
}
private function setUpSharedObject():void
{
chat_so = SharedObject.getRemote("chat", connection.uri);
chat_so.addEventListener(SyncEvent.SYNC, onSync);
chat_so.client = this;
}
private function onNetStatus(event:NetStatusEvent):void
{
if (event.info.code == "NetConnection.Connect.Success")
{
setUpSharedObject();
}
else
{
trace(event.info.code + ": " + event.info.description);
}
}
private function onSync(event:SyncEvent):void
{
for (var i:int = 0; i < event.changeList.length; i++)
{
var code:String = event.changeList[i].code;
switch(code)
{
case "change":
case "success":
{
messages.push();
dispatchEvent(new Event(Event.CHANGE));
break;
}
case "clear":
{
messages = [];
break;
}
case "delete":
default:
{
break;
}
}
}
}
}
}
来源:https://stackoverflow.com/questions/14140864/sharedobject-send-method