I have recently installed Apache2 and have just installed Tornado, I am following a couple of guides and have just created a simple websocket python script and associated index.html page.
As soon as I navigate to the IP address of my webserver on the Pi I receive a popup message (which is generated from the index.html page saying connection closed!!
This happens in Google Chrome and Safari, what have I done wrong?
Here is the server script:
Code: Select all
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'user is connected.\n'
def on_message(self, message):
print 'received message: %s\n' %message
self.write_message(message + ' OK')
def on_close(self):
print 'connection closed\n'
application = tornado.web.Application([(r'/ws', WSHandler),])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Code: Select all
<!doctype html>
<html>
<head>
<title>Websocket</title>
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
</head>
<body>
<h1>Websocket</h1>
<label id="conn_text"></label><br />
<input type="text" id="input_text"/>
<input type="submit" id="button" value="Send" /><br />
<div id="messages_txt" />
<script>
$(document).ready(function () {
//change example.com with your IP or your host
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function(evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Connection status: Connected!"
};
ws.onmessage = function(evt) {
var newMessage = document.createElement('p');
newMessage.textContent = "Server: " + evt.data;
document.getElementById('messages_txt').appendChild(newMessage);
};
ws.onclose = function(evt) {
alert ("Connection closed");
};
$("#button").click(function(evt) {
evt.preventDefault();
var message = $("#input_text").val();
ws.send(message);
var newMessage = document.createElement('p');
newMessage.textContent = "Client: " + message;
document.getElementById('messages_txt').appendChild(newMessage);
});
});
</script>
</body></html>