Skip to content

Instantly share code, notes, and snippets.

@atinsood
Created March 15, 2013 04:42
Show Gist options
  • Save atinsood/5167529 to your computer and use it in GitHub Desktop.
Save atinsood/5167529 to your computer and use it in GitHub Desktop.
Basic websocket server and client implemented in python using tornado....
import websocket
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
for i in range(20):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8888/ws",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
print "WebSocket opened"
def on_message(self, message):
print "Received message from client "+message
self.write_message(u"You said: " + message)
def on_close(self):
print "WebSocket closed"
application = tornado.web.Application([
(r'/ws', EchoWebSocket),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
@atinsood
Copy link
Author

Note that the chunk of this code has been borrowed from various links. I just modified some portions of it and published what worked best for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment