AS3 / AIR的readObject()从插座 - 你如何检查所有的数据已经被接收?有的、插座、数据、AIR

由网友(顾屿安歌)分享简介:如果你写一个简单的对象到套接字:If you write a simple object to a socket:var o:Object = new Object();o.type = e.type;o.params = e.params;_socket.writeObject(o);_socket.fl...

如果你写一个简单的对象到套接字:

If you write a simple object to a socket:

var o:Object = new Object();
o.type = e.type;
o.params = e.params;
_socket.writeObject(o);
_socket.flush();

然后在客户端上你只需使用:

Then on the client do you simply use:

private function onData(e:ProgressEvent):void
{
    var o:Object = _clientSocket.readObject();
}

还是你必须实现检查所有数据的某种方式调用之前已收到:收到 .readObject()

推荐答案

还有2的方法:

如果你有信心,你的对象放在一个包,你可以这样做:

If you're confident that your object will fit into one packet, you can do something like:

var fromServer:ByteArray = new ByteArray;

while( socket.bytesAvailable )
    socket.readBytes( fromServer );

fromServer.position = 0;
var myObj:* = fromServer.readObject();

如果你有具有多个包消息的可能性,然后一个常见用法是prePEND与该消息的长度的消息。类似的信息(伪code):

If you have the possibility of having multiple packet messages, then a common usage is to prepend the message with the length of the message. Something like (pseudo code):

var fromServer:ByteArray    = new ByteArray();
var msgLen:int              = 0;

while ( socket.bytesAvailable > 0 )
{
    // if we don't have a message length, read it from the stream
    if ( msgLen == 0 )
        msgLen = socket.readInt();

    // if our message is too big for one push
    var toRead:int  = ( msgLen > socket.bytesAvailable ) ? socket.bytesAvailable : msgLen;
    msgLen          -= toRead; // msgLen will now be 0 if it's a full message

    // read the number of bytes that we want.
    // fromServer.length will be 0 if it's a new message, or if we're adding more
    // to a previous message, it'll be appended to the end
    socket.readBytes( fromServer, fromServer.length, toRead );

    // if we still have some message to come, just break
    if ( msgLen != 0 )
        break;

    // it's a full message, create your object, then clear fromServer
}

而你的插座能够念想,这将意味着,多个数据包的消息将被正确读取,以及事实,你将不会错过,其中2个小消息被发送几乎同时(因为第一条消息将会把它的任何消息所有为一个消息,从而错过了第二个)

Having your socket able to read like this will mean that multiple packet messages will be read properly as well as the fact that you won't miss any messages where 2 small messages are sent almost simultaneously (as the first message will treat it all as one message, thereby missing the second one)

阅读全文

相关推荐

最新文章