WebSocket Draft 10向客户端写文本数据的实现

Posted on November 03, 2011 by Fdream

在Draft 10中,如果解析数据的过程弄清楚了,这个就更简单了,返回数据的格式和之前接受到的数据格式非常类似,只是你不用生成mask了,头部的其他格式还是一模一样的。

第一个字节还是固定的,是0×81,意义和接受数据的意义一样,第二个字节也是,后七个位表示数据长度,由于没有mask,所以第一位是0;长度的表示方法和接受的标识方法一致,可能用7位表示,也可能用16位表示。

用NodeJS实现如下:

var socketWriter = {
    'draft10': function(socket, data){
        var frames,
            length = new Buffer(data, 'utf8').length;
        if(data.length > 0x7d){
            frames = new Buffer(4);
            frames[0] = 0x81;
            frames[1] = 0x7e;
            frames[2] = length >> 8;
            frames[3] = length & 0xFF; //1111 1111
        }
        else{
            frames = new Buffer(2);
            frames[0] = 0x81;
            frames[1] = length;
        }

        if (socket.writable) {
            socket.write(frames, 'binary');
            socket.write(data, 'utf8');
            return true;
        }
        return false;
    },
    'draft76': function(socket, data){
        var byteLen = Buffer.byteLength(data, 'utf8'),
            bytes = new Buffer(byteLen + 2);

        bytes[0] = 0x00;
        bytes.write(data, 1, 'utf8');
        bytes[byteLen + 1] = 0xFF;

        return socket.write(bytes);
    }
};

socketWriter['draft75'] = socketWriter['draft76'];
分享 |
Categories:
Ajax Web
Tags:
,
Comments:
2 Comments
Views:
1,885 Views

Related Posts

2 Responses to <WebSocket Draft 10向客户端写文本数据的实现>

  1. 天宝哥哥 says:

    好专业,我不太懂,就看看。

  2. lite3 says:

    看了下你博客,蛮不错的,程序与美术的合体啊.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>