question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Threaded serve_forever

See original GitHub issue

Is there a way to run serve_forever asynchronously on its own thread. I am working on a Pi project that is utilizing websockets to easily stream sensor data to a web page. I am running into an issue with the serve_forever() function because it blocks everything else. Is there an easy way to thread it off to allow everything else to continue running?

Originally I had something along the lines of

def run():
    server.run_forever()
    # This code is never executed b/c server.run_forever
    while True:
        # Read photocell data
        light_level = readChannel(photocell)
        light_volts = convertVolts(light_level, 2)

I then tried something like this

def run():
    threading.Thread(target=server.run_forever()).start()
    # This still seems to block the thread...until  I hit 'Ctrl + C' which then appears
    # to allow code to continue executing and the socket server stays connected...
    while True:
        # Read photocell data
        light_level = readChannel(photocell)
        light_volts = convertVolts(light_level, 2)

Its weird that the threaded version allows me to hit Ctrl+C and the socket server appears to continue running and communicating with my webpage while letting my while statement run.

Is there a ‘proper’ way to thread this socket server that doesnt require me to hit Ctrl+C to allow code to continue?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
afreelandcommented, Nov 7, 2017

Not quite sure what I did but will put it here if it helps anything…

Was looking at different way to do threading in python and ran across this threading link.

I went into the websocket_server.py file and modified

def run_forever(self):
        try:
            logger.info("Listening on port %d for clients.." % self.port)
            self.serve_forever()

to this

def run_forever(self):
        try:
            logger.info("Listening on port %d for clients.." % self.port)
            # self.serve_forever()
            _serve = self.serve_forever
            # Start a thread with the server -- that thread will then start one
            # more thread for each request
            server_thread = threading.Thread(target=_serve)
            # Exit the server thread when the main thread terminates
            server_thread.daemon = True
            server_thread.start()

Not sure why or how…but now my app appears to start the socket server…continue along peacefully and connect to my browser client. Best accidental discovery I have made today lol

Is this something that could be useful for others?

2reactions
Pithikoscommented, Mar 6, 2018

You don’t have to do that. You should be able to run server_forever as a separate thread, similarly to how you did it.

I think the issue you first experienced was that you were passing threading.Thread(target=server.run_forever()) instead of (the correct) threading.Thread(target=server.run_forever). Notice that in the latter you are passing the function while in the first you are actually running the function.

Read more comments on GitHub >

github_iconTop Results From Across the Web

socketserver — A framework for network servers — Python ...
The ThreadingMixIn class defines an attribute daemon_threads, which indicates whether or not the server should wait for thread termination. You should set the ......
Read more >
How to stop a Socket serve_forever thread python 2.7
I'm fairly new to threading in Python, and I I've tried to initialize the thread without serve_forever, but I get the following:
Read more >
Python Examples of http.server.serve_forever
This page shows Python examples of http.server.serve_forever. ... Thread(target=self.server.serve_forever) self.server_thread.daemon = True ...
Read more >
threaded server
The server spawns a new thread for each client, and uses pthread_detach to ... client_free(c); return NULL; } static void serve_forever(int sk) {...
Read more >
SocketServer – Creating network servers. - Python Module of ...
Thread (target=server.serve_forever) t.setDaemon(True) # don't hang on exit t.start() logger = logging.getLogger('client') logger.info('Server on %s:%s', ip, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found