即時通訊框架T-io之WebSocket協議再之HelloWorld

z77z發表於2017-06-05

一.t-io是幹嘛的


這個框架已經開源到碼雲上面,介紹比較詳細,連結:git.oschina.net/tywo45/t-io,由於官方介紹中的入門程式客戶端和服務端都是用的java寫的,而且是用簡單的自定義TCP協議進行通訊的,也有一個websocket協議的列子,感覺有點複雜,不好入門。就想著使用javascript來做客戶端,t-io做服務端,採用websocket協議搞一個helloworld。

二.WebSocket協議咋回事


首先,t-io框架簡單說就是封裝一下些個:

  • 內建心跳檢測
  • 內建心跳傳送
  • 各種便捷的繫結API
  • 各種便捷的傳送API
  • 一行程式碼擁有自動重連功能
  • 各項訊息統計等功能,全部一鍵內建搞定,省卻各種煩惱

所以我們收到客戶端發來的websocket協議的包,在服務端就要做對應的解包,那我們還要了解websocket包的結構和通訊建立的過程:

①握手階段:

客戶端和伺服器建立TCP連線之後,客戶端傳送握手請求,隨後伺服器傳送握手響應即完成握手階段。如下:

客戶端握手請求類似如下:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com複製程式碼

伺服器的握手響應類似如下:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat複製程式碼

②握手成功後開始傳送資料幀

這是Websocket的資料傳輸協議,聊天資訊一般會按照這個協議的規則來傳輸,下圖中的一整個東西稱為一個資料幀,資料幀的成幀和解析是處理這個協議時最麻煩的一部分了。具體這個表怎麼看可以參照

0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 +-+-+-+-+-------+-+-------------+-------------------------------+
 |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
 |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
 |N|V|V|V|       |S|             |   (if payload len==126/127)   |
 | |1|2|3|       |K|             |                               |
 +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
 |     Extended payload length continued, if payload len == 127  |
 + - - - - - - - - - - - - - - - +-------------------------------+
 |                               |Masking-key, if MASK set to 1  |
 +-------------------------------+-------------------------------+
 | Masking-key (continued)       |          Payload Data         |
 +-------------------------------- - - - - - - - - - - - - - - - +
 :                     Payload Data continued ...                :
 + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
 |                     Payload Data continued ...                |
 +---------------------------------------------------------------+

 具體每一bit的意思
FIN      1bit 表示資訊的最後一幀
RSV 1-3  1bit each 以後備用的 預設都為 0
Opcode   4bit 幀型別,稍後細說
Mask     1bit 掩碼,是否加密資料,預設必須置為1 (這裡很蛋疼)
Payload  7bit 資料的長度
Masking-key      1 or 4 bit 掩碼
Payload data     (x + y) bytes 資料
Extension data   x bytes  擴充套件資料
Application data y bytes  程式資料複製程式碼

三.T-io服務端編寫


整體的編寫和框架自帶的Helloworld程式模式一致,需要改變的就是encode()編碼方法和decode()解碼方法,因為需要根據websocket協議來。

收到訊息後先解碼,再判斷包的型別,交給響應型別的handler。傳送訊息先編碼。

①握手

decode()解碼方法:

由於客戶端收到的第一個包是握手包,所以:

if (!barrageSessionContext.isHandshaked()) // 如果還沒有握手,則先進行握手操作
{
    if (BarragePacket.HANDSHAKE_BYTE == firstbyte) {
        buffer.position(1 + initPosition);
        return handshakePacket;
    } else {
        HttpRequestPacket httpRequestPacket = HttpRequestDecoder.decode(buffer);
        if (httpRequestPacket == null) {
            return null;
        }
        //交給握手包的Handler
        httpRequestPacket.setType(Type.COMMAND_HANDSHAKE_REQ);
        barrageSessionContext.setWebsocket(true);
        return httpRequestPacket;
    }
}

//握手成功後在barrageSessionContext中儲存此次連線的握手情況.
boolean isWebsocket = barrageSessionContext.isWebsocket();複製程式碼

握手包的Handler,返回握手響應包,讓客戶端知道握手成功,可以進行資料傳輸了,:

public class HandshakeReqHandler implements BarrageHandlerIntf<HandshakeBody> {

    private BarragePacket handshakeRespPacket = new BarragePacket(Type.COMMAND_HANDSHAKE_RESP);

    @Override
    public Object handler(
            BarragePacket packet,
            String body,
            ChannelContext<BarrageSessionContext, BarragePacket, Object> channelContext)
            throws Exception {
        BarrageSessionContext barrageSessionContext = channelContext.getSessionContext();
        barrageSessionContext.setHandshaked(true);

        boolean isWebsocket = barrageSessionContext.isWebsocket();
        if (isWebsocket)
        {
            HttpRequestPacket httpRequestPacket = (HttpRequestPacket) packet;
            HttpResponsePacket httpResponsePacket = updateWebSocketProtocol(httpRequestPacket);
            if (httpResponsePacket != null)
            {
                //傳送握手響應包,交給握手響應的handler
                httpResponsePacket.setType(Type.COMMAND_HANDSHAKE_RESP);
                Aio.send(channelContext, httpResponsePacket);
            } else
            {
                Aio.remove(channelContext, "不是websocket協議");
            }
        } else
        {
            Aio.send(channelContext, handshakeRespPacket);
        }
        return null;
    }

    public HttpResponsePacket updateWebSocketProtocol(HttpRequestPacket httpRequestPacket)
    {
        Map<String, String> headers = httpRequestPacket.getHeaders();

        String Sec_WebSocket_Key = headers.get("Sec-WebSocket-Key");

        if (StringUtils.isNotBlank(Sec_WebSocket_Key))
        {
            String Sec_WebSocket_Key_Magic = Sec_WebSocket_Key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            byte[] key_array = SHA1Util.SHA1(Sec_WebSocket_Key_Magic);
            String acceptKey = BASE64Util.byteArrayToBase64(key_array);
            HttpResponsePacket httpResponsePacket = new HttpResponsePacket();

            HttpResponseStatus httpResponseStatus = HttpResponseStatus.C101;
            httpResponsePacket.setHttpResponseStatus(httpResponseStatus);

            Map<String, String> respHeaders = new HashMap<>();
            respHeaders.put("Connection", "Upgrade");
            respHeaders.put("Upgrade", "WebSocket");
            respHeaders.put("Sec-WebSocket-Accept", acceptKey);
            httpResponsePacket.setHeaders(respHeaders);
            return httpResponsePacket;
        }
        return null;
    }

}複製程式碼

encode()編碼方法:

上面在握手包的handler中,呼叫了send方法,傳送了一個握手響應包,所以要在編碼的時候先判斷是否是握手響應包,對其編碼:

if (packet.getType() == Type.COMMAND_HANDSHAKE_RESP) {
    if (isWebsocket) {
        return HttpResponseEncoder.encode((HttpResponsePacket) packet, groupContext, channelContext);
    } else {
        ByteBuffer buffer = ByteBuffer.allocate(1);
        buffer.put(BarragePacket.HANDSHAKE_BYTE);
        return buffer;
    }
}複製程式碼

握手響應包的編碼

public static ByteBuffer encode(HttpResponsePacket httpResponsePacket, GroupContext<BarrageSessionContext, BarragePacket, Object> groupContext, ChannelContext<BarrageSessionContext, BarragePacket, Object> channelContext)
    {
        int bodyLength = 0;
        byte[] httpResponseBody = httpResponsePacket.getHttpResponseBody();
        if (httpResponseBody != null)
        {
            bodyLength = httpResponseBody.length;
        }

        StringBuilder sb = new StringBuilder(128);

        HttpResponseStatus httpResponseStatus = httpResponsePacket.getHttpResponseStatus();
        //        httpResponseStatus.get
        sb.append("HTTP/1.1 ").append(httpResponseStatus.getStatus()).append(" ").append(httpResponseStatus.getDescription()).append("\r\n");

        Map<String, String> headers = httpResponsePacket.getHeaders();
        if (headers != null && headers.size() > 0)
        {
            headers.put("Content-Length", bodyLength + "");
            Set<Entry<String, String>> set = headers.entrySet();
            for (Entry<String, String> entry : set)
            {
                sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
            }
        }
        sb.append("\r\n");

        byte[] headerBytes = null;
        try
        {
            headerBytes = sb.toString().getBytes("utf-8");
        } catch (Exception e)
        {
            throw new RuntimeException(e);
        }

        ByteBuffer buffer = ByteBuffer.allocate(headerBytes.length + bodyLength);
        buffer.put(headerBytes);

        if (bodyLength > 0)
        {
            buffer.put(httpResponseBody);
        }
        return buffer;
    }複製程式碼

②資料包

decode()解碼方法:

上面握手成功的時候會在BarrageSessionContext中儲存握手的情況。

if (isWebsocket) // 走的websocket協議
{
    WebsocketPacket websocketPacket = WebsocketDecoder.decode(buffer, channelContext);
    if (websocketPacket == null) {
        return null;
    }
    Opcode opcode = websocketPacket.getWsOpcode();
    if (opcode == Opcode.BINARY) {
        byte[] wsBody = websocketPacket.getWsBody();
        if (wsBody == null || wsBody.length == 0) {
            throw new AioDecodeException("錯誤的websocket包,body為空");
        }

        BarragePacket barragePacket = new BarragePacket(Type.COMMAND_HANDSHAKE_RESP);

        if (wsBody.length > 1) {
            byte[] dst = new byte[wsBody.length - 1];
            System.arraycopy(wsBody, 1, dst, 0, dst.length);
            barragePacket.setBody(dst);
        }
        return barragePacket;
    } else if (opcode == Opcode.PING || opcode == Opcode.PONG) {
        return heartbeatPacket;
    } else if (opcode == Opcode.CLOSE) {
        BarragePacket barragePacket = new BarragePacket(Type.COMMAND_CLOSE_REQ);
        return barragePacket;
    } else if (opcode == Opcode.TEXT) {
        byte[] wsBody = websocketPacket.getWsBody();
        if (wsBody == null || wsBody.length == 0) {
            throw new AioDecodeException("錯誤的websocket包,body為空");
        }
        BarragePacket barragePacket = new BarragePacket(Type.P2P_REQ);
        if (wsBody.length > 1) {
            barragePacket.setBody(wsBody);
        }
        return barragePacket;
    } else {
        throw new AioDecodeException("錯誤的websocket包,錯誤的Opcode");
    }

} else {
    if (BarragePacket.HEARTBEAT_BYTE == firstbyte) {
        buffer.position(1 + initPosition);
        return heartbeatPacket;
    }
}複製程式碼

資料包的handler:

public class P2PReqHandler implements BarrageHandlerIntf<P2PReqBody>{

    @Override
    public Object handler(
            BarragePacket packet,
            String jsonStr,
            ChannelContext<BarrageSessionContext, BarragePacket, Object> channelContext)
            throws Exception {
        System.out.println(jsonStr);
        BarragePacket barragePacket = new BarragePacket(Type.P2P_REQ);
        barragePacket.setBody(("收到了你的訊息,你的訊息是:" + jsonStr).getBytes(BarragePacket.CHARSET));
        Aio.send(channelContext, barragePacket);
        return null;
    }
}複製程式碼

這個收到訊息後的處理是,傳送收到的訊息到客戶端。

encode()編碼方法:

如果不是握手響應包,走websocket包的編碼
if (isWebsocket) {
    return WebsocketEncoder.encode(packet, groupContext, channelContext);
}複製程式碼
public static ByteBuffer encode(BarragePacket barragePacket, GroupContext<BarrageSessionContext, BarragePacket, Object> groupContext,
            ChannelContext<BarrageSessionContext, BarragePacket, Object> channelContext)
{
    byte[] websocketHeader;
    byte[] imBody = barragePacket.getBody();
    int wsBodyLength = 1; //固定有一個命令碼,佔一位
    if (imBody != null)
    {
        wsBodyLength += imBody.length;
    }

    byte header0 = (byte) (0x8f & (Opcode.BINARY.getCode() | 0xf0));

    if (wsBodyLength < 126)
    {
        websocketHeader = new byte[2];
        websocketHeader[0] = header0;
        websocketHeader[1] = (byte) wsBodyLength;
    } else if (wsBodyLength < ((1 << 16) - 1))
    {
        websocketHeader = new byte[4];
        websocketHeader[0] = header0;
        websocketHeader[1] = 126;
        websocketHeader[3] = (byte) (wsBodyLength & 0xff);
        websocketHeader[2] = (byte) ((wsBodyLength >> 8) & 0x80);
    } else
    {
        websocketHeader = new byte[6];
        websocketHeader[0] = header0;
        websocketHeader[1] = 127;
        int2Byte(websocketHeader, wsBodyLength, 2);
    }
    ByteBuffer buf = ByteBuffer.allocate(websocketHeader.length + wsBodyLength);
    buf.put(websocketHeader);

    buf.put(barragePacket.getType());

    if (imBody != null)
    {
        buf.put(imBody);
    }

    return buf;
}

public static void int2Byte(byte[] bytes, int value, int offset)
{
    checkLength(bytes, 4, offset);

    bytes[offset + 3] = (byte) ((value & 0xff));
    bytes[offset + 2] = (byte) ((value >> 8 * 1) & 0xff);
    bytes[offset + 1] = (byte) ((value >> 8 * 2) & 0xff);
    bytes[offset + 0] = (byte) ((value >> 8 * 3));
}

private static void checkLength(byte[] bytes, int length, int offset)
{
    if (bytes == null)
    {
        throw new IllegalArgumentException("null");
    }

    if (offset < 0)
    {
        throw new IllegalArgumentException("invalidate offset " + offset);
    }

    if (bytes.length - offset < length)
    {
        throw new IllegalArgumentException("invalidate length " + bytes.length);
    }
}複製程式碼

websocket協議的伺服器的處理流程大致是上面這個流程,但是程式碼我只貼了關鍵部分,完整的程式碼可以去我的碼雲上下載。

四.javascript客戶端編寫


<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
  <div>
    <input type="submit" value="Start" onclick="start()" />
  </div>
  <div id="messages"></div>
  <script type="text/javascript">
    var webSocket = 
      new WebSocket('ws://localhost:5678');

    webSocket.onerror = function(event) {
      onError(event)
    };

    webSocket.onopen = function(event) {
      onOpen(event)
    };

    webSocket.onmessage = function(event) {
      onMessage(event)
    };

    function onMessage(event) {
        var blob = event.data;
        var reader = new FileReader();
        reader.readAsText(blob, 'utf-8');
        reader.onload = function (e) {
            document.getElementById('messages').innerHTML 
            += '<br />' + reader.result;
        }
    }

    function onOpen(event) {
      document.getElementById('messages').innerHTML 
        = 'Connection established';
    }

    function onError(event) {
      alert(event.data);
    }

    function start() {
      webSocket.send('hellohellohellohellohellohellohellohellohe');
    }
  </script>
</body>
</html>複製程式碼

最好是下載程式下來,打上斷點,debug去跟一下,每一步包做了那些處理,變成了什麼樣子,傳輸的二進位制資料轉換成字串是甚麼樣子等等。

·······················································································································································

個人部落格:z77z.oschina.io/

此專案下載地址:git.oschina.net/z77z/spring…

·······················································································································································

相關文章