Small socket problem
Jean-Paul Calderone
exarkun at divmod.com
Mon Feb 9 10:24:47 EST 2009
On Mon, 9 Feb 2009 09:43:36 +0000, John O'Hagan <research at johnohagan.com> wrote:
>Hi,
>
>I'm using the socket module (python 2.5) like this (where 'options' refers to
>an optparse object) to connect to the Fluidsynth program:
>
> host = "localhost"
> port = 9800
> fluid = socket(AF_INET, SOCK_STREAM)
> try:
> fluid.connect((host, port)) #Connect if fluidsynth is running
> except BaseException:
> print "Connecting to fluidsynth..." #Or start fluidsynth
> soundfont = options.soundfont
> driver = options.driver
> Popen(["fluidsynth", "-i", "-s", "-g", "0.5",
> "-C", "1", "-R", "1", "-l", "-a", driver, "-j", soundfont])
> timeout = 50
> while 1:
> timeout -= 1
> if timeout == 0:
> print "Problem with fluidsynth: switching to synth."
> play_method = "synth"
> break
> try:
> fluid.connect((host, port))
> except BaseException:
> sleep(0.05)
> continue
> else:
> break
>
>(I'm using BaseException because I haven't been able to discover what
>exception class[es] socket uses).
>
>The problem is that this fails to connect ( the error is "111: Connection
>refused") the first time I run it after booting if fluidsynth is not already
>running, no matter how long the timeout is; after Ctrl-C'ing out of the
>program, all subsequent attempts succeed. Note that fluidsynth need not be
>running for a success to occur.
The most obvious problem is that you're trying to re-use a socket on which
a connection attempt has failed. This isn't allowed and will always fail.
You must create a new socket for each connection attempt.
You might also want to consider using a higher level socket library than
the "socket" module. The socket module exposes you to lots of very low
level details and platform-specific idiosyncrasies. You may find that a
library like Twisted (<http://twistedmatrix.com/>) will let you write
programs with fewer bugs.
Jean-Paul
More information about the Python-list
mailing list