码迷,mamicode.com
首页 > Web开发 > 详细

Websocket通讯简析

时间:2016-01-22 17:18:20      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

  • 什么是Websocket

Websocket是一种全新的协议,不属于HTTP无状态协议,协议名为"ws",这意味着一个Websocket连接地址会是这样的写法:ws://**。
Websocket协议本质上是一个基于TCP的协议。建立连接需要握手,客户端(浏览器)首先向服务器(web server)发起一条特殊的HTTP请求,web server解析后生成应答到浏览器,这样子一个Websocket连接就建立了,直到某一方关闭连接。

技术分享

1. Client try to connect to WebSocket server
2. Server recognize client
3. If client is not registered with server then add client (this is known as handshaking process which is based on headers transmission)
4. Send and receive data
5. Close connection

 

  • WebScoket数据帧

WebScoket协议中,数据以帧序列的形式传输,具体的协议标准可以参考rfc6455。
(1)客户端向服务器传输的数据帧必须进行掩码处理:服务器若接收到未经过掩码处理的数据帧,则必须主动关闭连接。
(2)服务器向客户端传输的数据帧一定不能进行掩码处理。客户端若接收到经过掩码处理的数据帧,则必须主动关闭连接。
针对上情况,发现错误的一方可向对方发送close帧(状态码是1002,表示协议错误),以关闭连接。

技术分享

 

  • 客户端API

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            function WebSocketTest() {
                if ("WebSocket" in window) {
                    alert("WebSocket is supported by your Browser!");
                    // Let us open a web socket
                    var ws = new WebSocket("ws://localhost:9998/echo");
                    ws.onopen = function () {
                        // Web Socket is connected, send data using send()
                        ws.send("Message to send");
                        alert("Message is sent...");
                    };
                    ws.onmessage = function (evt) {
                        var received_msg = evt.data;
                        alert("Message is received...");
                    };
                    ws.onclose = function () {
                        // websocket is closed.
                        alert("Connection is closed...");
                    };
                } else {
                    // The browser doesn‘t support WebSocket
                    alert("WebSocket NOT supported by your Browser!");
                }
            }
        </script>
    </head>
    <body>
        <div id="sse">
            <a href="javascript:WebSocketTest()">Run WebSocket</a>
        </div>
    </body>
</html>

 

  • 服务器端

各种语言类型的开源的Websocket Server都可以在网上找到。

例如Java的Spring WebSocket:https://github.com/search?utf8=%E2%9C%93&q=Spring+WebSocket

c语言:

https://github.com/gaccob/gbase/blob/master/net/wsconn.h

https://github.com/gaccob/gbase/blob/master/net/wsconn.c

 

  • 浏览器支持

技术分享

 

  • 参考文章

http://www.qixing318.com/article/643129914.html

http://zengrong.net/post/2199.htm

http://zh.wikipedia.org/wiki/WebSocket

http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/

http://blog.csdn.net/fenglibing/article/details/7100070

http://www.cnblogs.com/caosiyang/archive/2012/08/14/2637721.html

Websocket通讯简析

标签:

原文地址:http://www.cnblogs.com/gugia/p/5151244.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!