WebSocket握手服务端响应算法『java』

/ **
*GET / HTTP/1.1
 Upgrade: websocket
 Connection: Upgrade
 Host: localhost:50000
 Sec-WebSocket-Origin: http://localhost
 Sec-WebSocket-Key: BYEBkScKdCuqSKY2Mf6CIg==
 Sec-WebSocket-Version: 8
 Cookie:
*/
 public HashMap < String , String > getRequestHeader ( byte [ ] data ) {
 String requestHeader = new String ( data ) ;
 requestHeader = requestHeader . substring ( 0 , requestHeader . indexOf ( "\r\n\r\n" ) ) ;
String [ ] reqarr = requestHeader . split ( "\r\n" ) ;
reqHeader = new HashMap < String , String > ( ) ;
for ( int i = 0 ; i < reqarr . length ; i ++ ) {
 String requestHeaderLine = reqarr [ i ] ;
 if ( requestHeaderLine . toUpperCase ( ) . startsWith ( "GET" ) || requestHeaderLine . toUpperCase ( ) . startsWith ( "POST" ) ) {
 String [ ] first = requestHeaderLine . split ( " " ) ;
 if ( first . length == 3 ) {
 String method = first [ 0 ] ;
 String location = first [ 1 ] . replaceAll ( "\\s" , "" ) ;
 String protocol = first [ 2 ] . split ( "/" ) [ 0 ] ;
 String protocolVersion = first [ 2 ] . split ( "/" ) [ 1 ] ;
 reqHeader . put ( "Method" , method ) ;
 reqHeader . put ( "Location" , location ) ;
 reqHeader . put ( "Protocol" , protocol ) ;
 reqHeader . put ( "ProtocolVersion" , protocolVersion ) ;
 }
 } else {
 String [ ] reqlinearr = requestHeaderLine . split ( ":" ) ;
 if ( reqlinearr . length == 2 ) {
 String key = reqlinearr [ 0 ] ;
 String value = reqlinearr [ 1 ] . replaceAll ( "\\s" , "" ) ;
 reqHeader . put ( key , value . replaceAll ( "\\s" , "" ) ) ;
 }
 }
 }
return reqHeader ;
 }
 public String getResponseHeader ( ) {
 String originKey = reqHeader . get ( "Sec-WebSocket-Key" ) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ;
 java . security . MessageDigest alga = null ;
 byte [ ] digesta = null ;
 try {
 alga = java . security . MessageDigest . getInstance ( "SHA-1" ) ;
 alga . update ( originKey . getBytes ( ) ) ;
 digesta = alga . digest ( ) ;
 } catch ( NoSuchAlgorithmException e ) {
 e . printStackTrace ( ) ;
 }
 byte [ ] respKey = org . apache . commons . codec . binary . Base64 . encodeBase64 ( digesta ) ;
 String header = "HTTP/1.1 101 Switching Protocols\r\n" +
 "Upgrade: Websocket\r\n" +
 "Connection: Upgrade\r\n" +
 "Sec-WebSocket-Accept: " + new String ( respKey ) + "\r\n\r\n" ;
 return header ;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值