如果您将一个简单的对象写入套接字:
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()
发布评论