来自套接字的 AS3/AIR readObject()

编程入门 行业动态 更新时间:2024-10-28 20:29:03
本文介绍了来自套接字的 AS3/AIR readObject() - 您如何检查是否已收到所有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果您将一个简单的对象写入套接字:

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()

推荐答案

有两种方法:

如果您确信您的对象可以装入一个包中,您可以执行以下操作:

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();

如果您可能有多个数据包消息,那么常见的用法是在消息前面加上消息的长度.类似(伪代码):

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)

更多推荐

来自套接字的 AS3/AIR readObject()

本文发布于:2023-11-23 15:13:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AIR   readObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!