Last active
March 1, 2018 04:08
-
-
Save imjamespond/3f9c9033a7cb332b5da63f2c7535d68b to your computer and use it in GitHub Desktop.
web camera
This file contains 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
with python and js |
This file contains 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> | |
<head> | |
<meta charset="utf-8" /> | |
<title></title> | |
</head> | |
<body> | |
<script> | |
navigator.mediaDevices.getUserMedia({ audio: true, video: true }) | |
.then(function(stream) { | |
/* use the stream */ | |
console.log("stream is ready") | |
}) | |
.catch(function(err) { | |
/* handle the error */ | |
console.log(err) | |
}); | |
</script> | |
</body> | |
</html> | |
common.js | |
var socket; | |
function createSocket(address, name) { | |
socket = new WebSocket(address) | |
socket.binaryType = "arraybuffer" | |
socket.onclose = function(ev){ | |
console.log(ev) | |
} | |
socket.onerror = function(ev){ | |
console.log(ev) | |
} | |
socket.onmessage = function(ev){ | |
console.log(ev) | |
} | |
socket.onopen = function(ev){ | |
console.log(ev) | |
socket.send(JSON.stringify({'type': 'NULL'})); | |
} | |
//socket.close(code?: number, reason?: string): void; | |
//socket.send(data: any): void; | |
} |
This file contains 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
WEB_ROOT=. | |
ACTION=${1:-'run'} | |
case $# in | |
0) ;; | |
2) WEB_ROOT=$2 | |
;; | |
*) echo "Usage: $0 run <WEB ROOT>" | |
;; | |
esac | |
if [ "$ACTION" = "setup" ]; then | |
cnpm install http-server | |
elif [ "$ACTION" = "run" ]; then | |
./node_modules/http-server/bin/http-server $WEB_ROOT -c-1 -g | |
fi |
This file contains 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
from __future__ import print_function | |
import BaseHTTPServer, SimpleHTTPServer | |
import ssl | |
import sys, os | |
import argparse | |
import json | |
import logging | |
import Handlers | |
from threading import Thread | |
os.chdir('./web') | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--http_port', type=int, default=8000, help='Http Port') | |
parser.add_argument('--ws_port', type=int, default=9000, help='WebSocket Port') | |
args = parser.parse_args() | |
'''Adopted from https://www.piware.de/2011/01/creating-an-https-server-in-python/''' | |
def http_srv(port): | |
httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', port), SimpleHTTPServer.SimpleHTTPRequestHandler) | |
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile = 'key.pem', certfile='cert.pem', server_side=True) | |
print('now serving tls http on port:', port) | |
httpd.serve_forever() | |
from autobahn.twisted.websocket import WebSocketServerProtocol, \ | |
WebSocketServerFactory | |
from twisted.internet import task, defer | |
from twisted.internet.ssl import DefaultOpenSSLContextFactory | |
from twisted.python import log | |
class MyServerProtocol(WebSocketServerProtocol): | |
def __init__(self): | |
super(MyServerProtocol, self).__init__() | |
self.handlers = {} | |
self.handlers['foobar'] = Handlers.foobar | |
self.handlers['recv-frame'] = Handlers.recvFrame | |
def onConnect(self, request): | |
print("Client connecting: {}".format(request.peer)) | |
def onOpen(self): | |
print("WebSocket connection open.") | |
def onMessage(self, payload, isBinary): | |
''' | |
if isBinary: | |
log.msg("Binary message received: {} bytes".format(len(payload))) | |
else: | |
log.msg("Text message received: {}".format(payload.decode('utf8'))) | |
''' | |
raw = payload.decode('utf8') | |
msg = json.loads(raw) | |
result = {} | |
if msg['type'] == "NULL": | |
result['type'] = "error" | |
elif msg['type'] : | |
handler = self.handlers[msg['type']] | |
if handler is not "NULL": | |
result = handler(msg) | |
self.sendMessage(json.dumps(result), isBinary) | |
def onClose(self, wasClean, code, reason): | |
print("WebSocket connection closed: {}".format(reason)) | |
def start_websocket_server(reactor): | |
log.startLogging(sys.stdout) | |
factory = WebSocketServerFactory() | |
factory.protocol = MyServerProtocol | |
ctx_factory = DefaultOpenSSLContextFactory('key.pem', 'cert.pem') | |
reactor.listenSSL(args.ws_port, factory, ctx_factory) | |
return defer.Deferred() | |
if __name__ == '__main__': | |
thread = Thread() | |
thread.run = lambda: http_srv(int(args.http_port)) | |
thread.daemon = True | |
thread.start() | |
task.react(start_websocket_server) | |
#thread.join() |
This file contains 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
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 | |
You can also add -nodes if you don't want to protect your private key with a passphrase, | |
otherwise it will prompt you for "at least a 4 character" password. | |
The days parameter (365) you can replace with any number to affect expiration date. | |
It will then prompt you for things like "Country Name" but you can just hit enter and accept defaults. | |
Self-signed certs are not validated with any third party unless you import them to the browsers previously. | |
If you need more security, you should use a certificate signed by a CA. | |
openssl rsa -in key.pem -out newkey.pem && mv newkey.pem key.pem | |
remove the password |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pip install git+https://github.com/Pithikos/python-websocket-server