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

一.t-io是幹嗎的


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

二.WebSocket協議咋回事


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

  • 內置心跳檢測
  • 內置心跳發送
  • 各類便捷的綁定API
  • 各類便捷的發送API
  • 一行代碼擁有自動重連功能
  • 各項消息統計等功能,所有一鍵內置搞定,省卻各類煩惱

因此咱們收到客戶端發來的websocket協議的包,在服務端就要作對應的解包,那咱們還要了解websocket包的結構和通訊創建的過程:java

①握手階段:git

客戶端和服務器創建TCP鏈接以後,客戶端發送握手請求,隨後服務器發送握手響應即完成握手階段。以下:web

客戶端握手請求相似以下:spring

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複製代碼

服務器的握手響應相似以下:json

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

②握手成功後開始發送數據幀springboot

這是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協議來。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…

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

相關文章
相關標籤/搜索