Created
April 7, 2013 05:23
-
-
Save patrickhulce/5329147 to your computer and use it in GitHub Desktop.
Working with web sockets.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import socket, threading, time, re | |
| from base64 import b64encode | |
| from hashlib import sha1 | |
| def handle(s,a): | |
| print a | |
| handshake_data = s.recv(4096) | |
| print handshake_data | |
| client_key = re.search("Sec-WebSocket-Key:\s+(.*?)[\n\r]+", handshake_data).groups()[0].strip() | |
| handshake_response = ( | |
| 'HTTP/1.1 101 Web Socket Protocol Handshake', | |
| 'Upgrade: WebSocket', | |
| 'Connection: Upgrade', | |
| 'WebSocket-Location: ws://localhost:9876/', | |
| 'Sec-WebSocket-Accept: {hashed_key}\r\n\r\n' | |
| ) | |
| WSID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" | |
| server_key = b64encode(sha1(client_key + WSID).digest()) | |
| response = "\r\n".join(handshake_response).format(hashed_key=server_key) | |
| print response | |
| s.send(response) | |
| time.sleep(10) | |
| print "sending hello" | |
| s.send('\x00hello\xff') | |
| print "sending world" | |
| time.sleep(1) | |
| s.send('\x00world\xff') | |
| msg = s.recv(4096) | |
| print msg | |
| #s.close() | |
| s = socket.socket() | |
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| s.bind(('', 9876)); | |
| s.listen(1); | |
| print "Now listening on port 9876" | |
| while 1: | |
| t,a = s.accept(); | |
| print "Connection received" | |
| threading.Thread(target = handle, args = (t,a)).start() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html xmlns="http://www.w3.org/1999/xhtml"> | |
| <head> | |
| <title>Web Socket Example</title> | |
| <meta charset="UTF-8"> | |
| <script> | |
| window.onload = function() { | |
| var s = new WebSocket("ws://localhost:9876/"); | |
| s.onopen = function(e) { | |
| alert("opened"); | |
| s.send("\x00testing\xFF"); | |
| } | |
| s.onclose = function(e) { | |
| alert(e.toString()); | |
| } | |
| s.onmessage = function(e) { | |
| alert("got something!"); | |
| console.log(e.data); | |
| } | |
| s.onerror = function(e) { | |
| alert("something fucked up"); | |
| } | |
| }; | |
| </script> | |
| </head> | |
| <body> | |
| <div id="holder" style="width:600px; height:300px"></div> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment