user3599803
user3599803

Reputation: 7004

python websocket with tornado. Socket aren't closed

I'm a beginner with websocket, I'm trying to use tornado for that purpose. Here is my working code so far:

from tornado import websocket
from tornado import web
import tornado.ioloop

class EchoWebSocket(websocket.WebSocketHandler):
    def open(self):
        print "WebSocket opened"

    def on_message(self, message):
        self.write_message(u"You said: " + message)
        print message

    def on_close(self):
        print "WebSocket closed"

    def check_origin(self, origin):
        return True

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([(r"/", EchoWebSocket),(r'/',MainHandler),])
application.listen(8001)
tornado.ioloop.IOLoop.instance().start()

I'm using IDLE, and everything is working fine so far, only one annoying problem. I can't fix this code and than re-run the server without seeing this error:

    application.listen(8001)
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1691, in listen
    server.listen(port, address)
  File "C:\Python27\lib\site-packages\tornado\tcpserver.py", line 125, in listen
    sockets = bind_sockets(port, address=address)
  File "C:\Python27\lib\site-packages\tornado\netutil.py", line 137, in bind_sockets
    sock.bind(sockaddr)
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

It seems that python doesn't close the socket when I terminate the program. The only way I found is to terminate the python process in task manager, than I have my port 'free' again.
Why this is happening, and what can be done (it's really hard working like that..)? Why OS won't free the my port ?

Upvotes: 0

Views: 2395

Answers (1)

piergiaj
piergiaj

Reputation: 629

You need to stop the server so that the port is available for use again.

This will stop the server:

tornado.ioloop.IOLoop.instance().stop()

You should call when you are done running the server (if you kill it with CTRL-C, you need to catch that and call this in the handler).

You can catch CTRL-C with this:

import signal
def signal_handler(signum, frame):
    tornado.ioloop.IOLoop.instance().stop()

signal.signal(signal.SIGINT, signal_handler)

Upvotes: 4

Related Questions