3

I'm trying to create a server-side application to listen for connections and call a method based on what the client says. However when I call the method upload i want to continue executing code under main.

Is there anyway i can achieve this, or am i taking the incorrect approach? Code below;

def main(ipAddr, tcpPort, bufferSize, s):
    try:
        s.bind((ipAddr, tcpPort))
        s.listen(4)
        conn, addr = s.accept()

    print("Connection attempt from: %s" % addr)
    messageRecv = ""
    while True:
        data = conn.recv(bufferSize)
        if not data: break
        messageRecv = data.decode('utf-8')
finally:
    conn.close()
    if messageRecv == "Ready": upload(addr)

main(ipAddr, tcpPort, bufferSize, s)



def upload(addr):
    pass
PacketLoss
  • 5,561
  • 1
  • 9
  • 27
  • 1
    I would recommend to read about Multithreaded Programming. you can see this [tutorial](https://www.tutorialspoint.com/python/python_multithreading.htm) – omri_saadon Jun 07 '17 at 16:00
  • 3
    Fix the indentation, please. – Nurjan Jun 07 '17 at 16:01
  • If you are on a recent version of Python, you want to take a look at the [`asyncio` package](https://docs.python.org/3/library/asyncio.html). For older versions of Python, use [Twisted](https://twistedmatrix.com/). – Sven Marnach Jun 07 '17 at 16:06

1 Answers1

1

Consider using the multiprocessing module, which is essentially Python's "multithreading" package. The API is very similar to the threading module's, but threading may be prohibitive due to the GIL.

In your case, you may have something like this:

p = Process(target=upload, args=(addr,))
p.start()
# some other code
p.join()
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 1
    I support this answer but I will however always recommend that you give a shot at [gevent](http://www.gevent.org/) a much lightweight solution to a multi-thread / multi process paradigm. And if you are interested into asyncIO in server side try also [Tornado](http://www.tornadoweb.org/en/stable/0) – SRC Jun 07 '17 at 16:08
  • 1
    Python's threading module is very often useful, and networking is a prime example of an application of threading. The GIL is a non-issue for many applications, since most applications aren't CPU-bound, but rather I/O-bound. – Sven Marnach Jun 07 '17 at 16:08
  • 1
    @SvenMarnach Fair enough; I guess that statement was somewhat harsh. – arshajii Jun 07 '17 at 16:12
  • 1
    An useful SO thread with example of using Tornado - https://stackoverflow.com/questions/22920877/simple-async-example-with-tornado-python – SRC Jun 07 '17 at 16:15