Hello,

Here I go again.

I have the simplest of ideas...yet cannot seem to find a solution to implement it:

from socket import *
import time
BUFSIZE = 256
IP = 'localhost'
PORT = 25000
ADDR =(IP, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)    
tcpCliSock.connect(ADDR)

tcpCliSock.send('I want a response from you server')

#Here I would like to have a while and print dots 
#each second that goes by without an answer

#print
#while len(resp)==0:
#    resp = tcpCliSock.recv(BUFSIZE)
#    print '.'
#    time.sleep(1)
#print

resp = tcpCliSock.recv(BUFSIZE)
print 'I've received:',recv

I've tried the socket setdefaulttimeout(), but that makes the program exit when timeout is reached for socket read. I've thought of a thread but seems too damn complicated for such a simple idea. Isn't there a way to give the socket read a Timeout value like in C (setsockopt() using a timeval structure)?

I'll welcome any idea:)...

Till soon,

Recommended Answers

All 2 Replies

OK, I tried a simple idea (the example I gave was just to illustrate, I actually have a class and a receive method).

So I made an exterior function

#imports and stuff...

FlagDots = False

def PrintDots():  
    global FlagDots
    while FlagDots:  
        sys.stdout.write('.')
        time.sleep(1)

class MyClass:
    def Receive(self):
        global FlagDots
        #start printing dots
        FlagDots = True  
        t = thread.start_new_thread(PrintDots,())  
#when the function exits, the thread does too...
        
        self.Received = self.Socket.recv(BUFSIZ)
        
        #Stop printing dots
        FlagDots = False

Now It works (I use receive for requests that sometimes take time responding on the other side )...

I'd just like your opinion if the thread dies silently when PrintDots exits (which is what I understood from the reference of 'thread' (since there is no exit function). Otherwise I am starting a never ending thread for each time I call Receive...

Reference Python :http://www.python.org/doc/2.4.2/lib/module-thread.html

start_new_thread( function, args[, kwargs])
Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

What do you think?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.