librelist archives

« back to archive

opening a socket at new port in flaskapp

opening a socket at new port in flaskapp

From:
Chengi Liu
Date:
2013-02-12 @ 09:38
Starting another socket on a separate thread...

Long story short.. I am trying to start a server @localhost:13373
But i want this server to run on background.. hence writing on a thread..
but somehow i am getting an error which seems like the thread is trying to
open a socket again.
Any clue if its a flask thingy or python thingy.

My server code is this:


    import SocketServer
    import json

    class MyTCPServer(SocketServer.ThreadingTCPServer):
        allow_reuse_address = True


    class MyTCPServerHandler(SocketServer.BaseRequestHandler):
        def handle(self):
            try:
                data = json.loads(self.request.recv(1024).strip())
                # process the data, i.e. print it:
                print data
                # send some 'ok' back
                self.request.sendall(json.dumps({'return': 'ok'}))
            except Exception, e:
                print "Exception wile receiving message: ", e

    def socket_server(host,port):
        print host,port
        server = MyTCPServer((host, port), MyTCPServerHandler)
        server.serve_forever()


And I am trying to call this from a script like this


    import threading
    server_thread = threading.Thread(target=socket_server,
args=('127.0.0.1', 13373))
    server_thread.start()
    app.run()
    #after this i have other code..

So while it starts the server....and everything is fine but somehow.. it
tries to start the same code again..

because i see this error:



        Exception in thread Thread-1:
    Traceback (most recent call last):


    127.0.0.1 13373   <---- THIS IS THE PORT WHICH IS CONNECTED
    Exception in thread Thread-1:
    Traceback (most recent call last):
      File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py",
line 530, in __bootstrap_inner
        self.run()
      File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py",
line 483, in run
        self.__target(*self.__args, **self.__kwargs)
      File
"/Users/mohitdeepsingh/Desktop/project/flaskapp/app/sock_lib/sock_server.py",
line 21, in socket_server
        server = MyTCPServer((host, port), MyTCPServerHandler)
      File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py",
line 408, in __init__
        self.server_bind()
      File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py",
line 419, in server_bind
        self.socket.bind(self.server_address)
      File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py",
line 222, in meth
        return getattr(self._sock,name)(*args)
    error: [Errno 48] Address already in use


So basically what i am trying to do is call socket_server(host,port) in
background and just continue with my code.