开发者

How to read data from an XMLSocket in as3?

开发者 https://www.devze.com 2023-03-07 19:14 出处:网络
While using Socket, I am able to read the data as while (socket.bytesAvailable) { textArea.text += socket.readUTFBytes(socket.bytesAvailable);

While using Socket, I am able to read the data as

while (socket.bytesAvailable) 
{
    textArea.text += socket.readUTFBytes(socket.bytesAvailable);
}

How ca开发者_如何学Cn I read the data while using an XMLSocket? Is it enough to use xmlSocket.toString() ?


No, with XMLSocket receiving data is event driven, you create a socket, set up event handlers:

socket = new XMLSocket();   
socket.addEventListener(Event.CLOSE, closeHandler, false, 0, true);
socket.addEventListener(Event.CONNECT, connectHandler, false, 0, true);
socket.addEventListener(DataEvent.DATA, dataHandler, false, 0, true);
socket.addEventListener(IOErrorEvent.IO_ERROR, errorHandler, false, 0, true);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityHandler, false, 0, true);    

socket.connect(host, port);

you will receive data in dataHandler:

private function dataHandler(e: DataEvent): void {  
   var xml: XML = XML(e.data);
   ...
}

Now you can process XML using whatever means you want. Sending is easier, but still you have to take into account that you are not connectd immediately after calling connect, you have to wait until connectHandler gets called before sending data:

var xml: XML = ...
if (socket.connected) {
  socket.send(xml);
}


socket.addEventListener(DataEvent.DATA, onData);

private function onData(event:DataEvent):void {
    trace(event.data);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消