Websocket communication with python server

Friday, July 11, 2014

I'm trying to set up a simple Python server to send data to websocket. The problem is when server sends data to websocket - nothing happens(i have on.open, on.message, on.error functions) Strange thing is server reads(found it out through error log) the message WS sends, on.message triggers, no errors. Any help? Here's the code for both client and server:



import socket
import sys
from hashlib import sha1
from base64 import b64encode
import time
import binascii
import struct



host = 'localhost'
port = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
demi = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
MAGIC = demi.encode("UTF-8")


handshaken = False

def decode(datax):
frame = bytearray(datax)
length = frame[1]&127
indexFirstMask = 2
if length == 126:
indexFirstMask = 4
elif length == 127:
indexFirstMask = 10

indexFirstDataByte = indexFirstMask + 4
masks = [m for m in frame[indexFirstMask:indexFirstDataByte]]
i = indexFirstDataByte
j = 0
dec = []
while i < len(frame):
dec.append(chr((frame[i] ^ masks[j % 4])))
j += 1
i += 1
return(dec)

def splitz(header):
words = header.split()
for i in range(len(words)):
if(words[i] == 'Sec-WebSocket-Key:'):
key = words[i+1]
break
return key

print("Listening 9999")

handshake = ''
header = ''

client, address = sock.accept()
while True:
if handshaken == False:
header += client.recv(1024).decode()
key = splitz(header).encode("UTF-8")
one = sha1(key+MAGIC)
two = b64encode(one.digest())
handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
handshake += "Upgrade: websocket\r\n"
handshake += "Connection: Upgrade\r\n"
handshake += "Sec-WebSocket-Accept: "+two.decode()+"\r\n\r\n"
if header.find('\r\n\r\n') != -1:
data = header.split('\r\n\r\n', 1)[1]
handshaken = True
client.send(handshake.encode())
else:
data = ''
tmpd = client.recv(1024)
dataw = decode(tmpd)
for i in dataw:
data = data + i
print(data)
data = '\x00' + data + '\xff'
data = data.encode()
client.sendall(data)


Websocket client(very simple testing with some leftovers that doesn't matter):



<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script type="application/javascript">
var ws;

function init() {

ws = new WebSocket("ws://localhost:9999/");
ws.onopen = function(){
ws.send("Hello");
console.log("sent init mess")
};
ws.onmessage = function(e){
console.log("");
}
ws.onerror = function(e){
cinsole.log("ddfs");
}
}
</script>
</head>
<body onload="init();">
<div id="servermsg"><h1>Message log:</h1></div>
</body>
</html>






http://ift.tt/1r3SSC5