viernes, 15 de marzo de 2013

[Solution] “socket.error: Address already in use” in python

yesterday in the evening i was writing a simple web server in python (2.7) and i got a socket error when i tried restart my “simple web server” so i digged a lot and few time later i found the answer, so here leave my python's script to fix that error.
#!/usr/bin/env python

import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class http_handler(SimpleHTTPRequestHandler):
    pass

class TCPServer(SocketServer.TCPServer):
    """
    this is a variable that may be overridden by derived classes or
    instances
    i found it at '/usr/lib/python2.7/SocketServer.py'
    """
    allow_reuse_address = True

server_addr = ('127.0.0.1',8000)
httpd = TCPServer(server_addr, http_handler)
print "listening on: %s:%d" % (server_addr[0], server_addr[1])
httpd.serve_forever()
and here is the explanation:
some forums says that you have to set the variable “allow_reuse_address” hosted in the TCPServer class to “True” with a magical
“myTCPServerInstance.allow_reuse_address  = True”
Note: that it comes from the very base class socket, where that variable it's a synonym of “socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, True)” to set the socket address in reuse mode.
But it doesn't work! as easy like they says, so digging a few in the python's help (SocketServer's help) i watched that you must to override the variable “allow_reuse_address “ hosted in the TCPServer class with a value of True because by default it's False so here is the code that i overrode:
class TCPServer(SocketServer.TCPServer):
    """
    this is a variable that may be overridden by derived classes or
    instances
    i found this at '/usr/lib/python2.7/SocketServer.py'
    """
    allow_reuse_address = True
and that's it! to run the script you should use:
python webserver.py
in your terminal

No hay comentarios: