1.WebSocket介绍

1.1 概念

WebSocket是HTML5中一系列新的API,或者说新规范,新技术。支持页面上使用Web Socket协议与远程主机进行全双工的通信。它引入了WebSocket接口并且定义了一个全双工的通信通道,通过一个单一的套接字在Web上进行操作。

1.2 websocket vs HTTP

首先,web技术发展经历了以下阶段。

静态页面(html)

动态页面(cgi,j2ee,php...)

Ajax技术

comet技术(轮询)

1.2.1 实现方案对比

举个简单的例子,以51cto的消息推送为例。

下面,就用提到的技术实现这个小小的功能,分析下利弊。

静态页面就不说了,它一般应用在页面缓存级别,但消息条目明显有一定时效的,不适用该场景。

动态页面,为了更新消息数目,刷新整个页面,下面所有的页面重新渲染,效率也不加。

ajax技术,可以实现局部页面刷新,通过HTTP轮询,获取消息条目。即使没有新消息,也必须发送请求,产生无意义的请求。请求间隔太长,实时性存在问题;间隔太端,浪费服务器资源和占用带宽。

comet技术,基于HTTP长连接,是反向Ajax(Reverse Ajax)一种实现,能够从服务器端向客户端发送数据,实现了连接的复用。 两种实现方式各有利弊。(1)基于Ajax的长轮询(long-polling)方式;(2)基于 Iframe 及 htmlfile 的流(http streaming)方式。

websocket实现方案

与http协议不同的请求/响应模式不同,HTML5 Web Sockets以最小的开销高效地提供了Web连接 ,极大的减少了不必要的网络流量与延迟。一个Web客户端通过websocket连接到一个远程端点,进行全双工的通信,提高了实时性,不存在浪费服务资源问题。

1.2.2 websocket 与http关系

两者都是应用层的开发规范,websocket是基于http的,Websocket其实是一个新协议,跟HTTP协议基本没有关系,只是为了兼容现有浏览器的握手规范而已。

http支持长连接;但websocket是持久连接。

1.3 websocket场景

1.社交订阅

2.多玩家游戏

3.协同编辑/编程

4.点击流数据

5.股票基金报价

6.体育实况更新
7.多媒体聊天
8.基于位置的应用

9.在线教育

2. 我的websocket 项目

项目还在不断完善之中。里面包含了若干个websocket例子。例子,包括游戏类,聊天类,画板类....

本人,比较喜欢学一门技术的原则“无论如何先跑起来”,搜集这些例子,花费了个人近3天时间。

希望对大家有用。

项目地址:https://github.com/janecms/websocket_example

3. 声明服务端websocket服务(Endpoint)的两种方式

最主要的内容就是声明EndPoint。

创建服务端步骤

Create an endpoint class.

Implement the lifecycle methods of the endpoint.

Add your business logic to the endpoint.

Deploy the endpoint inside a web application.

3.1编程式

Endpoint中的onOpen,onClose,onError对应websocket的生命周期。

1.创建Endpoint

publicclassEchoEndpointextendsEndpoint{@OverridepublicvoidonOpen(finalSessionsession,EndpointConfigconfig){session.addMessageHandler(newMessageHandler.Whole<String>(){@OverridepublicvoidonMessage(Stringmsg){try{session.getBasicRemote().sendText(msg);}catch(IOExceptione){...}}});}}

2.部署endpoint

ServerEndpointConfig.Builder.create(EchoEndpoint.class,"/echo").build();

具体参见:

https://github.com/janecms/websocket_example中的<websocket.echo.EchoEndpoint>.

3.2 注解声明式

更简单。

@ServerEndpoint("/echo")publicclassEchoEndpoint{@OnMessagepublicvoidonMessage(Sessionsession,Stringmsg){try{session.getBasicRemote().sendText(msg);}catch(IOExceptione){...}}}

具体参见

https://github.com/janecms/websocket_example中的<websocket.echo.EchoAnnotation>.

相关annotation说明

Each websocket endpoint may only have one message handling method for each of the native websocket
message formats: text, binary and pong

一个endpoint只能有一个被@OnMessage修饰的处理文本,二进制,pone信息的的方法。这个限制,不同的环境,会有所区别。

4.html5 websocket 实现客户端

客户端,也对应生命周期。onOpen,onClose,onMessage,onError。

varwsocket;functionconnect(){wsocket=newWebSocket("ws://localhost:8080/dukeetf2/dukeetf");wsocket.onmessage=onMessage;//定义回调websocket.onerror=function(evt){onError(evt)};}functiononMessage(evt){vararraypv=evt.data.split("/");document.getElementById("price").innerHTML=arraypv[0];document.getElementById("volume").innerHTML=arraypv[1];}...window.addEventListener("load",connect,false);

5. websocket协议交互数据

和标准HTTP,存在很大不同。

5.1 请求数据

GET/path/to/websocket/endpointHTTP/1.1Host:localhostUpgrade:websocketConnection:UpgradeSec-WebSocket-Key:xqBt3ImNzJbYqRINxEFlkg==Origin:http://localhostSec-WebSocket-Version:13

5.2 响应数据

HTTP/1.1101SwitchingProtocolsUpgrade:websocketConnection:UpgradeSec-WebSocket-Accept:K7DJLdLooIwIG/MOpvWFB3y3FE8=

5.3 websocket的请求URL,也不是标准http schema。

普通:ws://host:port/path?query加密:wss://host:port/path?query

参考资源

https://www.oschina.net/translate/9-killer-uses-for-websockets

http://www.tuicool.com/articles/FBbaai

https://docs.oracle.com/javaee/7/tutorial/websocket.htm

https://github.com/janecms/websocket_example

结论

主要讲了websocket与http的异同,以及websoket的优势和使用场景。简单探讨了2中声明websocket方式。最后分享了自己的展示项目。 接下来,通过案例实战,演练编码解码,错误处理在websocket的使用。