如何从响应中提取数据(套接字)

时间:2014-05-28 08:24:09

标签: actionscript-3 sockets

我需要一些帮助来从响应套接字中提取数据。准确地说是onResponse函数中Trace()的输出。

var socket:Socket = new Socket();
var codehtml:String = "test";

function onConnect(e:Event):void {
    socket.writeUTFBytes("GET / HTTP/1.1\n");
    socket.writeUTFBytes("Host: 192.168.1.2\n");
    socket.writeUTFBytes("\n");
}


function onResponse(e:ProgressEvent):void {
    if (socket.bytesAvailable>0) {
        var tmpcode:String = socket.readUTFBytes(socket.bytesAvailable);
        trace(tmpcode);
    }
}

socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);

socket.connect("www.google.fr", 80);

1 个答案:

答案 0 :(得分:0)

套接字的问题在于信息对于单个数据包来说可能太大了。所以你可以收到一半的信息,然后收到剩下的信息。

通常,这是通过'EOF'(文件结束)分隔符处理的 - 一个与消息结尾匹配的特殊字符。例如,您可以收到这两个数据包:

  1. <start><body>some text
  2. </body></start>$
  3. 这应该是常规的xml数据,但是您无法仅从第一个数据包中获取它。所以你需要等待一切都来。但你怎么知道它发生了?等待这个特殊的$标志。

    这是必要的,因为有时候信息不足以被投射到可读的东西上。这是一个简单的解决方案:

    const EOL_DELIMITER:String = '$';
    var _buffer:String = "";
    
    _socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
    
    function onSocketData(event:ProgressEvent):void
    {
        var data:String = _socket.readUTFBytes(_socket.bytesAvailable);
        _buffer += data; // add everything to a buffer that will store all info until now
    
        var msg:String;
        var index:int;
    
        // this will search for the delimeter
        // as long as there is one - there is a message
        // it's in a loop as there might be several messages in one packet
        // if there is no message, this loop will fail and only the buffer will get filled
        while((index = _buffer.indexOf(EOL_DELIMITER)) > -1)
        {
            msg = _buffer.substring(0, index);
            _buffer = _buffer.substring(index + 1); // clear the message from the buffer
    
            // new message has arrived -> msg var
        }
    }
    

    希望有所帮助!