How to allow ws:// instead of localhost:// for tornado - python

I have the following basic tornado app:
import tornado.web
class IndexHandler(tornado.web.RequestHandler):
"""Regular HTTP handler to serve the ping page"""
def get(self):
self.write("OK")
if __name__ == "__main__":
app = tornado.web.Application([
(r"/", IndexHandler),
])
app.listen(8000)
print 'Listening on 0.0.0.0:8000'
tornado.ioloop.IOLoop.instance().start()
This will run on "http://localhost:8000". How would I get this to run and accept connections at ws://localhost:8000?

tornado.web.RequestHandler is used for accepting HTTP requests. For websockets, you need to use tornado.websocket.WebSocketHandler.
Another thing to note is that you can't visit a websocket url directly from the browser. That is, you can't type ws://localhost:8000 in the address bar and expect to connect to the websocket. That is not how websockets work.
A websocket connection is an upgrage connection. Which means, you first have to visit a url via HTTP and then use Javascript to upgrade to websocket.
See an example about how to connect to websocket using Javascript at Mozilla Web Docs.

Related

How to handle individual socket.io client events in python?

I am primarily a Javascript developer but I am trying to replicate a server I wrote in Node.js in Python. The server uses Socket.io to communicate with clients and I am having some trouble replicating this specific behaviour in Python:
io.on('connection', function(socket){
socket.on('disconnect', function(){ });
});
I would like to handle each client's events and messages separately from one another. Any way I could do this in Python? I am using the package flask_socketio to wrap the sockets. Cheers.
As far as I can see you just want connection and disconnection handlers?
You can do that as follows in Python:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on('connect')
def connect():
# your connection logic here
#socketio.on('disconnect')
def disconnect():
# your disconnection logic here
if __name__ == '__main__':
socketio.run(app)

Add https redirect in Python3 Mockserver

we have this mockserver that is now serving https:// requests, and if we remove the ssl wrapping (ssl.wrap_socket(myServer.socket,keyfile='key.pem',certfile= 'cert.pem', server_side=True), the server only serves http:// requests. Is there any way where we can make this server to support both requests. Our objective is when the server receives an http:// request, it will automatically convert it as https:// and process the request.
Thanks in advance for the support
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl
class Mock(BaseHTTPRequestHandler):
-------------------
-------------------
def main():
global hostname, port
hostname = "127.0.0.1"
port = 8000
myServer = HTTPServer((hostname, port), Mock)
myServer.socket = ssl.wrap_socket(myServer.socket,keyfile='key.pem',certfile= 'cert.pem', server_side=True)
myServer.serve_forever()
if __name__ =="__main__":
main()
If the HTTP and HTTPS servers need different functionality, then it makes sense to make them two different instances. Why not make a second HTTPServer that is only HTTP that simply returns a 302 status with the Location header pointing to the HTTPS mock server (but using the same path).

Running eventlet server in bottle framework

i see something like this in bottle.py version 0.9. Does that means. i can run bottle server as a eventlet server.
class EventletServer(ServerAdapter):
""" Untested """
def run(self, handler):
from eventlet import wsgi, listen
wsgi.server(listen((self.host, self.port)), handler
)
Atlast figured out. how to run bottle server as eventlet in bottle framework.Just should pass the argument server='' inside run. list of supported servers Server adapters in bottle
run(server='eventlet',host='localhost', port=8080, reloader=True)

How to write a web server using twisted?

How do i write a simple http web server using twisted framework?
I want a web server that can receive http request and return a response to the client.
Am going through the twisted documentation and am kinda confused (maybe am just lazy), but it does not look very direct on how to do this, especially how does the twisted server receive the request parameters?
This is my effort...
from twisted.web import proxy, http
from twisted.internet import reactor
from twisted.python import log
from twisted.protocols import basic
import sys
log.startLogging(sys.stdout)
class InformixProtocol(basic.LineReceiver):
def lineReceived(self, user):
self.transport.write("Hello this is twisted web server!")
self.transport.loseConnection()
class ProxyFactory(http.HTTPFactory):
#protocol = proxy.Proxy
protocol = InformixProtocol
reactor.listenTCP(8080, ProxyFactory())
reactor.run()
Thanks
Gath

Basic SSL Server Using Twisted Not Responding

I am currently trying to pull together a basic SSL server in twisted. I pulled the following example right off their website:
from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol
class Echo(Protocol):
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
print "dataReceived: %s" % data
self.transport.write(data)
if __name__ == '__main__':
factory = Factory()
factory.protocol = Echo
print "running reactor"
reactor.listenSSL(8080, factory,
ssl.DefaultOpenSSLContextFactory(
"./test/privatekey.pem", "./test/cacert.pem"))
reactor.run()
I then tried to hit this server using firefox by setting the url to https://localhost:8080 yet I receive no response. I do, however, see the data arriving at the server. Any ideas why I'm not getting a response?
You're not sending an http header back to the browser, and you're not closing the connection
You've implemented an SSL echo server here, not an HTTPS server. Use the openssl s_client command to test it interactively, not firefox (or any other HTTP client, for that matter).

Categories