websockets handshake using netcat/bash script

 

During the process of learning websockets, wanted to try out the handshake mechanism using a simple server cooked using netcat/bash script. The script just reads the request message, parses the key, forms the SHA1/base64 response key and sends the response.

Tested it with chromium. Attached are the code and screenshot.

#!/bin/bash
rm -rf t
while true
do
   read packet
   echo $packet >> t
   cnt=`echo $packet | wc -c`
   if [ $cnt == 2 ] #end of message
   then
      key=`cat t | grep "Sec-WebSocket-Key:" | cut -f2 -d " "`
      keylen=`echo -n $key | wc -c`
      keylen=`expr $keylen - 1`
      key2=`echo -n $key | cut -c -$keylen`
      magic="258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
      resp=`echo -n $key2$magic | openssl sha1 -binary | base64`
      echo   -n "HTTP/1.1 101 Switching Protocols"$'\r\n'
      echo   -n "Connection: Upgrade"$'\r\n'
      echo   -n "Upgrade: websocket"$'\r\n'
      echo   -n "Sec-WebSocket-Accept: $resp"$'\r\n\r\n'
      break
   fi
done

HTML with websocket call

<script>
function start() {
var connection = new WebSocket('ws://localhost:8888/websocket');
connection.onopen = function () {
  alert('open');
};
}
</script>
<html>
<body onload="javascript:start();">
</body>
</html>

nvoke netcat as follows and open the above HTML using chromium/firefox

nc -l -p 8888 -e ./wshandshake.sh 

Screenshot of Chromium websocket developer console, post invocation.

 

Copy from http://ssklogs.blogspot.com/2012/10/websockets-handshake-using-netcatbash.html

posted @ 2013-06-01 11:26  sunsweet  阅读(544)  评论(0编辑  收藏  举报