[Python] Some doubts in threading

Discussion in 'Mixed Languages' started by Tito, Feb 24, 2014.

  1. Tito

    Tito Super Mod / Adviser
    Staff Member

    Nov 30, 2009
    18,681
    18,587
    340
    #1 Tito, Feb 24, 2014
    Last edited by a moderator: Apr 20, 2017
    Out of curiosity, I'm trying to implement a UDP (yes, no TCP) file exchange utility using Python for my Android phone & PC.

    The sample code for the receiver is:
    Code:
    from socket import *
    import sys
    import select
    
    host="0.0.0.0"
    port = 9999
    s = socket(AF_INET,SOCK_DGRAM)
    s.bind((host,port))
    
    addr = (host,port)
    buf=1024
    
    data,addr = s.recvfrom(buf)
    print "Received File:",data.strip()
    f = open(data.strip(),'wb')
    
    data,addr = s.recvfrom(buf)
    try:
        while(data):
            f.write(data)
            s.settimeout(2)
            data,addr = s.recvfrom(buf)
    except timeout:
        f.close()
        s.close()
        print "File Downloaded"
    
    The sample code for the sender is:
    Code:
    from socket import *
    import sys
    
    s = socket(AF_INET,SOCK_DGRAM)
    host = raw_input("Enter host address:  ")
    port = 9999
    buf =1024
    addr = (host,port)
    
    file_name= raw_input("Enter file name:  ")
    
    s.sendto(file_name,addr)
    
    f=open(file_name,"rb")
    data = f.read(buf)
    while (data):
        if(s.sendto(data,addr)):
            print "sending ..."
            data = f.read(buf)
    s.close()
    f.close()
    
    Now I want to modify the receiver part so that it is capable of receiving multiple files from different devices simultaneously. Any thought?? Threading??

    Note that I have no prior knowledge in Python (in fact very little in programming :D). Most of the codes are inspired by Python documentation & stackoverflow.com.
     
  2. Tito

    Tito Super Mod / Adviser
    Staff Member

    Nov 30, 2009
    18,681
    18,587
    340
    Bump! Anyone?

    :confused:
     
  3. Pr3acher

    Pr3acher MDL Member

    Aug 24, 2012
    143
    48
    10
    Heya, well I know this is kinda old but anyways, could still help a bit, tho I ain't python master :') . So yes use threading, (import threading). You basically need 2 functions. One will just bind and listen and in an infinite loop, it will just accept incomming connections. This will return the data. Then from here call another function which will process the data. So params to this function are data and socket. Thing here is to call this function in a thread: threading.Thread(None, self.process_con, None, (sock, data), None).