Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8543739
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T12:22:45+00:00 2026-06-11T12:22:45+00:00

I’m trying to set up a small example of a public Twitter stream over

  • 0

I’m trying to set up a small example of a public Twitter stream over websockets. This is my websocket.py, and it’s working.

What I’m wondering is: how can I interact with the websocket from ‘outside’ the class WSHandler (ie. not only answer when receiving a message from websocket.js)? Say I want to run some other function within this same script that would post “hello!” every five seconds and send that to the websocket (browser) without any interaction from client-side. How could I do that?

So it’s kind of a fundamental beginner’s question, I suppose, about how to deal with classes as those below. Any pointers in any direction would be greatly appreciated!

import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

# websocket
class FaviconHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/static/favicon.ico')

class WebHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hi, client: connection is made ...")

    def on_message(self, message):
        print 'message received: \"%s\"' % message
        self.write_message("Echo: \"" + message + "\"")
        if (message == "green"):
            self.write_message("green!")

    def on_close(self):
        print 'connection closed'



handlers = [
    (r"/favicon.ico", FaviconHandler),
    (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
    (r'/', WebHandler),
    (r'/ws', WSHandler),
]

settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), "static"),
)

application = tornado.web.Application(handlers, **settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T12:22:46+00:00Added an answer on June 11, 2026 at 12:22 pm

    You could call a

    IOLoop.add_timeout(deadline, callback)
    

    that calls the callback at specified deadline timeout (one shot, but you can reschedule), or use the

    tornado.ioloop.PeriodicCallback if you have a more periodic task.

    See: http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_timeout

    Update: some example

    import datetime
    
    def test():
        print "scheduled event fired"
    ...
    
    if __name__ == "__main__":
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888)
        main_loop = tornado.ioloop.IOLoop.instance()
        # Schedule event (5 seconds from now)
        main_loop.add_timeout(datetime.timedelta(seconds=5), test)
        # Start main loop
        main_loop.start()
    

    it calls test() after 5 seconds.

    Update 2:

    import os.path
    import tornado.httpserver
    import tornado.websocket
    import tornado.ioloop
    import tornado.web
    
    # websocket
    class FaviconHandler(tornado.web.RequestHandler):
        def get(self):
            self.redirect('/static/favicon.ico')
    
    class WebHandler(tornado.web.RequestHandler):
        def get(self):
            self.render("websockets.html")
    
    class WSHandler(tornado.websocket.WebSocketHandler):
        def open(self):
            print 'new connection'
            self.write_message("Hi, client: connection is made ...")
            tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=5), self.test)
    
        def on_message(self, message):
            print 'message received: \"%s\"' % message
            self.write_message("Echo: \"" + message + "\"")
            if (message == "green"):
                self.write_message("green!")
    
        def on_close(self):
            print 'connection closed'
    
        def test(self):
            self.write_message("scheduled!")
    
    handlers = [
        (r"/favicon.ico", FaviconHandler),
        (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
        (r'/', WebHandler),
        (r'/ws', WSHandler),
    ]
    
    settings = dict(
        template_path=os.path.join(os.path.dirname(__file__), "static"),
    )
    
    application = tornado.web.Application(handlers, **settings)
    
    import datetime
    
    if __name__ == "__main__":
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
Does anyone know how can I replace this 2 symbol below from the string
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.