---
title: "WebSocket不同版本的三种握手方式以及一个Netty实现JAVA类"
author: "mmdev"
date: "2011-12-29T10:45:00Z"
tags: []
slug: "websocket-netty-java"
draft: false
lastmod: "2012-05-28T09:41:33Z"
id: 1542524
url: "https://mmdev.iteye.com/blog/1542524"
---

**一、WebSocket不同版本的三种握手方式**

WebSocket是HTML5中的新特性，应用也是非常的广泛，特别是用户WEB端与后台服务器的消息通讯，如阿里的WEBWW就是使用的WebSocket与后端服务器建立长连接进行的通讯。目前WebSocket还处于发展当中，就目前的发展过程而言，WebSocket现在不同的版本，有三种不同的握手方式：

1、基于Flash的WebSocket通讯，使用场景是IE的多数版本，因为IE的多数版本不都不支持WebSocket协议，以及FF、CHROME等浏览器的低版本，还没有原生的支持WebSocket，可以使用FLASH的WebSocket实现进行通讯：

浏览器请求：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. GET/lsHTTP/1.1
2. Upgrade:WebSocket
3. Connection:Upgrade
4. Host:www.xx.com
5. Origin:http://www.xx.com

服务器回应：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. HTTP/1.1101WebSocketProtocolHandshake
2. Upgrade:WebSocket
3. Connection:Upgrade
4. WebSocket-Origin:http://www.xx.com
5. WebSocket-Location:ws://www.xx.com/ls

**原理：**

如果客户端没有发送Origin请求头，则客户端不需要返回，如果客户端没有发送`WebSocket-Protocol请求头，服务端也不需要返回；服务端唯一需要组装返回给客户端做为校验的就是WebSocket-Location请求头，拼装一个websocket请求的地址就可以了。`

这种方式，是最老的一种方式，连一个安全Key都没有，服务端也没有对客户的请求做加密性校验。

2、第二种握手方式是带两个安全key请求头的，结果以md5加密，并放在body中返回的方式，参看如下示例：

浏览器请求：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. GET/demoHTTP/1.1
2. Host:example.com
3. Connection:Upgrade
4. Sec-WebSocket-Key2:129985Y31.P00
5. Sec-WebSocket-Protocol:sample
6. Upgrade:WebSocket
7. Sec-WebSocket-Key1:4@146546xW%0l15
8. Origin:http://example.com
9. ^n:ds[4U

服务器回应：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. HTTP/1.1101WebSocketProtocolHandshake
2. Upgrade:WebSocket
3. Connection:Upgrade
4. Sec-WebSocket-Origin:http://example.com
5. Sec-WebSocket-Location:ws://example.com/demo
6. Sec-WebSocket-Protocol:sample
7. 8jKS’y:G\*Co,Wxa-

**原理：**

在请求中的“Sec-WebSocket-Key1”, “Sec-WebSocket-Key2”和最后的“^n:ds[4U”都是随机的，服务器端会用这些数据来构造出一个16字节的应答。

把第一个Key中的数字除以第一个Key的空白字符的数量，而第二个Key也是如此。然后把这两个结果与请求最后的8字节字符串连接起来成为一个字符串，服务器应答正文（“8jKS’y:G\*Co,Wxa-”）即这个字符串的MD5 sum。

3、第三种是带一个安全key的请求，结果是先以“SHA-1”进行加密，再以base64的加密，结果放在Sec-WebSocket-Accept请求头中返回的方式：

浏览器请求：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. GET/lsHTTP/1.1
2. Upgrade:websocket
3. Connection:Upgrade
4. Host:www.xx.com
5. Sec-WebSocket-Origin:http://www.xx.com
6. Sec-WebSocket-Key:2SCVXUeP9cTjV+0mWB8J6A==
7. Sec-WebSocket-Version:8

服务器回应：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. HTTP/1.1101SwitchingProtocols
2. Upgrade:websocket
3. Connection:Upgrade
4. Sec-WebSocket-Accept:mLDKNeBNWz6T9SxU+o0Fy/HgeSw=

**原理：**

握手的实现，首先要获取到请求头中的Sec-WebSocket-Key的值，再把这一段GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"加到获取到的Sec-WebSocket-Key的值的后面，然后拿这个字符串做SHA-1 hash计算，然后再把得到的结果通过base64加密，就得到了返回给客户端的Sec-WebSocket-Accept的http响应头的值。

还可以参看我前面专门针对这种协议写的一篇文章：[http://blog.csdn.net/fenglibing/article/details/6852497](http://blog.csdn.net/fenglibing/article/details/6852497)

**二、基于Netty实现JAVA类**

为了支持以上提到的三种不同版本的websocket握手实现，服务端就需要针对这三种情况进行相应的处理，以下是一段基于netty实现的java代码，一个完整的WebSocketHelper实现：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

001. importjava.io.UnsupportedEncodingException;
002. importjava.security.MessageDigest;
003. importjava.security.NoSuchAlgorithmException;
004. importorg.jboss.netty.buffer.ChannelBuffer;
005. importorg.jboss.netty.buffer.ChannelBuffers;
006. importorg.jboss.netty.handler.codec.http.DefaultHttpResponse;
007. importorg.jboss.netty.handler.codec.http.HttpHeaders;
008. importorg.jboss.netty.handler.codec.http.HttpHeaders.Names;
009. importorg.jboss.netty.handler.codec.http.HttpRequest;
010. importorg.jboss.netty.handler.codec.http.HttpResponse;
011. importorg.jboss.netty.handler.codec.http.HttpResponseStatus;
012. importorg.jboss.netty.handler.codec.http.HttpVersion;
013. publicclassWebSocketHelper{
014. privatefinalstaticStringSEC\_WEBSOCKET\_KEY="Sec-WebSocket-Key";
015. privatefinalstaticStringSEC\_WEBSOCKET\_ACCEPT="Sec-WebSocket-Accept";
016. /\*websocket版本号：草案8到草案12版本号都是8，草案13及以后的版本号都和草案号相同\*/
017. privatefinalstaticStringSec\_WebSocket\_Version="Sec-WebSocket-Version";
018. /\**
019. \*判断是否是WebSocket请求
020. \*
021. \*@paramreq
022. \*@return
023. \*/
024. publicbooleansupportWebSocket(HttpRequestreq){
025. return(HttpHeaders.Values.UPGRADE.equalsIgnoreCase(req.getHeader(HttpHeaders.Names.CONNECTION))&&HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(req.getHeader(HttpHeaders.Names.UPGRADE)));
026. }
027. /\**
028. \*根据WebSocket请求，判断不同的握手形式，并返回相应版本的握手结果
029. \*
030. \*@paramreq
031. \*@return
032. \*/
033. publicHttpResponsebuildWebSocketRes(HttpRequestreq){
034. StringreasonPhrase="";
035. booleanisThirdTypeHandshake=Boolean.FALSE;
036. intwebsocketVersion=0;
037. if(req.getHeader(Sec\_WebSocket\_Version)!=null){
038. websocketVersion=Integer.parseInt(req.getHeader(Sec\_WebSocket\_Version));
039. }
040. /\**
041. \*在草案13以及其以前，请求源使用http头是Origin，是草案4到草案10，请求源使用http头是Sec-WebSocket-Origin，而在草案11及以后使用的请求头又是Origin了，
042. \*不知道这些制定WEBSOCKET标准的家伙在搞什么东东，一个请求头有必要变名字这样变来变去的吗。&lt;br&gt;
043. \*注意，这里还有一点需要注意的就是"websocketVersion&gt;=13"这个条件，并不一定适合以后所有的草案，不过这也只是一个预防，有可能会适应后面的草案，如果不适合还只有升级对应的websocket协议。&lt;br&gt;
044. \*/
045. if(websocketVersion&gt;=13
046. ||(req.containsHeader(Names.SEC\_WEBSOCKET\_ORIGIN)&&req.containsHeader(SEC\_WEBSOCKET\_KEY))){
047. isThirdTypeHandshake=Boolean.TRUE;
048. }
049. //websocket协议草案7后面的格式，可以参看wikipedia上面的说明，比较前后版本的不同：http://en.wikipedia.org/wiki/WebSocket
050. if(isThirdTypeHandshake=Boolean.FALSE){
051. reasonPhrase="SwitchingProtocols";
052. }else{
053. reasonPhrase="WebSocketProtocolHandshake";
054. }
055. HttpResponseres=newDefaultHttpResponse(HttpVersion.HTTP\_1\_1,newHttpResponseStatus(101,reasonPhrase));
056. res.addHeader(HttpHeaders.Names.UPGRADE,HttpHeaders.Values.WEBSOCKET);
057. res.addHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.UPGRADE);
058. //Fillintheheadersandcontentsdependingonhandshakemethod.
059. if(req.containsHeader(Names.SEC\_WEBSOCKET\_KEY1)&&req.containsHeader(Names.SEC\_WEBSOCKET\_KEY2)){
060. //Newhandshakemethodwithachallenge:
061. res.addHeader(Names.SEC\_WEBSOCKET\_ORIGIN,req.getHeader(Names.ORIGIN));
062. res.addHeader(Names.SEC\_WEBSOCKET\_LOCATION,getWebSocketLocation(req));
063. Stringprotocol=req.getHeader(Names.SEC\_WEBSOCKET\_PROTOCOL);
064. if(protocol!=null){
065. res.addHeader(Names.SEC\_WEBSOCKET\_PROTOCOL,protocol);
066. }
067. //Calculatetheanswerofthechallenge.
068. Stringkey1=req.getHeader(Names.SEC\_WEBSOCKET\_KEY1);
069. Stringkey2=req.getHeader(Names.SEC\_WEBSOCKET\_KEY2);
070. inta=(int)(Long.parseLong(getNumeric(key1))/getSpace(key1).length());
071. intb=(int)(Long.parseLong(getNumeric(key2))/getSpace(key2).length());
072. longc=req.getContent().readLong();
073. ChannelBufferinput=ChannelBuffers.buffer(16);
074. input.writeInt(a);
075. input.writeInt(b);
076. input.writeLong(c);
077. ChannelBufferoutput=null;
078. try{
079. output=ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5").digest(input.array()));
080. }catch(NoSuchAlgorithmExceptione){
081. }
082. res.setContent(output);
083. }elseif(isThirdTypeHandshake=Boolean.FALSE){
084. Stringprotocol=req.getHeader(Names.SEC\_WEBSOCKET\_PROTOCOL);
085. if(protocol!=null){
086. res.addHeader(Names.SEC\_WEBSOCKET\_PROTOCOL,protocol);
087. }
088. res.addHeader(SEC\_WEBSOCKET\_ACCEPT,getSecWebSocketAccept(req));
089. }else{
090. //Oldhandshakemethodwithnochallenge:
091. if(req.getHeader(Names.ORIGIN)!=null){
092. res.addHeader(Names.WEBSOCKET\_ORIGIN,req.getHeader(Names.ORIGIN));
093. }
094. res.addHeader(Names.WEBSOCKET\_LOCATION,getWebSocketLocation(req));
095. Stringprotocol=req.getHeader(Names.WEBSOCKET\_PROTOCOL);
096. if(protocol!=null){
097. res.addHeader(Names.WEBSOCKET\_PROTOCOL,protocol);
098. }
099. }
100. returnres;
101. }
102. privateStringgetWebSocketLocation(HttpRequestreq){
103. return"ws://"+req.getHeader(HttpHeaders.Names.HOST)+req.getUri();
104. }
105. privateStringgetSecWebSocketAccept(HttpRequestreq){
106. //CHROMEWEBSOCKETVERSION8中定义的GUID，详细文档地址：http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10
107. Stringguid="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
108. Stringkey="";
109. key=req.getHeader(SEC\_WEBSOCKET\_KEY);
110. key+=guid;
111. try{
112. MessageDigestmd=MessageDigest.getInstance("SHA-1");
113. md.update(key.getBytes("iso-8859-1"),0,key.length());
114. byte\[]sha1Hash=md.digest();
115. key=base64Encode(sha1Hash);
116. }catch(NoSuchAlgorithmExceptione){
117. }catch(UnsupportedEncodingExceptione){
118. }
119. returnkey;
120. }
121. Stringbase64Encode(byte\[]input){
122. sun.misc.BASE64Encoderencoder=newsun.misc.BASE64Encoder();
123. Stringbase64=encoder.encode(input);
124. returnbase64;
125. }
126. //去掉传入字符串的所有非数字
127. privateStringgetNumeric(Stringstr){
128. returnstr.replaceAll("\\\\D","");
129. }
130. //返回传入字符串的空格
131. privateStringgetSpace(Stringstr){
132. returnstr.replaceAll("\\\\S","");
133. }
134. }

**三、注意事项**

不同版本的WebSocket标准，编码和解码的方式还有所不同，在第一种和第二种WebSocket协议标准中，使用Netty自带的Encoder和Decoder即可：

org.jboss.netty.handler.codec.http.websocket.WebSocketFrameEncoder  
org.jboss.netty.handler.codec.http.websocket.WebSocketFrameDecoder

而如果要支持第三种实现标准，Netty目前官方还不支持，可以到github中找到实现的Encoder及Decoder：

[https://github.com/joewalnes/webbit/tree/0356ba12f5c21f8a297a5afb433215bb2f738008/src/main/java/org/webbitserver/netty](https://github.com/joewalnes/webbit/tree/0356ba12f5c21f8a297a5afb433215bb2f738008/src/main/java/org/webbitserver/netty)

不过，它的实现有一点问题，就是没有处理客户端主动发起的WebSocket请求断开，既客户端主动发起opcode为8的请求，不过它还是有预留的，找到这个类：

Hybi10WebSocketFrameDecoder

的包含这以下内容的行：

} else if (this.opcode == OPCODE\_CLOSE) {

在其中插入：

return new DefaultWebSocketFrame(0x08, frame);

然后在你的实现子类中增加如下的代码判断即可：

[view plain](http://blog.csdn.net/fenglibing/article/details/7100070 "view plain")[copy to clipboard](http://blog.csdn.net/fenglibing/article/details/7100070 "copy to clipboard")[print](http://blog.csdn.net/fenglibing/article/details/7100070 "print")[?](http://blog.csdn.net/fenglibing/article/details/7100070 "?")

1. if(frame.getType()==0x08){
2. //处理关闭事件的XXX方法
3. return;
4. }