【问题标题】:AS3 - How to know when a Socket has no more data to return?AS3 - 如何知道 Socket 何时没有更多数据要返回?
【发布时间】:2026-02-21 14:40:01
【问题描述】:

我正在尝试使用this 协议进行通信。它工作正常,除非套接字有很多数据要返回。现在我正在检查一个数据包是否以 \r\n 结尾,以确定我是否收到了所有的包。问题是有时一个包可以以 \r\n 作为换行符结束,即使它不是最后一个包,所以我不能使用它。

我正在使用命令队列,因为我想在发送下一个命令之前等待完整的响应。

删除了不必要的代码:

class CustomSocket extends Socket
{

    private var _response:String;
    private var _commandQueue:Array;

    public function CustomSocket()
    {
        super();
        this.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
    }

    private function socketDataHandler(event:ProgressEvent):void 
    {
        readResponse();
    }

    private function readResponse():void {
        var str:String = this.readUTFBytes(bytesAvailable);
        _response += str;
        //BUG: I cannot use this check for determining the end of packets, need to find a new one
        if (_response.charAt(_response.length - 1) == "\n" && _response.charAt(_response.length - 2) == "\r")
        {
            //dispatch the result
            commandFinished();
        }
    }

    //writes to the socket
    private function sendRequest(request:String):void 
    {
        _response = "";
       this. writeln(request);
        flush();
        writeln("\r\n");
        flush();
    }

    private function writeln(str:String):void 
    {
        try
        {
            this.writeUTFBytes(str);
        }
        catch (e:IOError) 
        {
            trace(e);
        }
    }

    private function addCommand():void
    {
        //adds a command to the queue and executes it
    }

    private function commandFinished():void
    {
        //remove executed command and check if there is more commands in the queue to execute
    }
}

问题出在函数 readResponse 中。我用谷歌搜索了很多,但没有找到任何感兴趣的东西。

有没有办法知道套接字将返回的字节/数据包的总量?或者一种检测 EOF 或包是最后一个包的方法?

【问题讨论】:

    标签: flash actionscript-3 sockets actionscript


    【解决方案1】:

    通常,在您发送的数据末尾会发送一个空字符。
    这为您的服务器提供了一个明确的字符来寻找。

    this.writeln(request + String.fromCharCode(0) );
    

    只是为了让你知道
    此行的函数 sendRequest 中的点后有一个空格

    this. writeln(request);
    

    您可能还想尝试此方法进行错误处理。

    if(this.connected){
      this.writeln(request + String.fromCharCode(0) );
      this.flush();
    }else{
      // do your error handling for no connection to server
    }
    

    【讨论】:

      【解决方案2】:

      您可能正在寻找 Socket 上的 bytesAvailable 属性。如:

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

      对于更完整的解决方案(包括可以一次获取多条消息的地方),我在另一个问题中回答了这个问题: AS3 / AIR readObject() from socket - How do you check all data has been received?

      【讨论】: