how to know if socket is still connected

nephish at xit.net nephish at xit.net
Sun Jul 16 19:20:24 EDT 2006


Grant Edwards wrote:
> On 2006-07-16, nephish at xit.net <nephish at xit.net> wrote:
>
> > serverhost = 'xxx.xxx.xxx.xxx'
> > serverport = 9520
> > aeris_sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > aeris_sockobj.connect((serverhost,serverport))
> >
> > while 1:
> >     do this or that with socket,
> >     send and receive info.
> >     yadda yadda yadda
> >
> > works well, but sometimes the server drops the connection. so,
> > what i need is something that will let me know if the
> > connection is still ok, if not will reconnect.
>
> If the server has closed the connection, then a recv() on the
> socket will return an empty string "", and a send() on the
> socket will raise an exception.
>
> > what i thought, since it only lets you connect on a certain
> > port one at a time, that i could use a try-except to connect
> > every time, if it could not connect (because it already is)
> > then i would just continue on. But if it is not connected, it
> > would reconnect. that is what brings me here. Seems like it
> > would work, but is there a better way?
>
> I don't see why the normal send() and recv() semantics aren't
> sufficient.
>
> --
> Grant Edwards                   grante             Yow!  I'm an East Side
>                                   at               TYPE...
>                                visi.com



like this ?
databack = aeris_sockobj.recv(2048)
 if databack:
            view_msg = 'caught request acknowlage %s bytes \n' %
len(databack)
else:
            view_msg = 'fail to recieve data from aeris server\n'

then put the reconnect in the else: block ?

thanks


thanks




More information about the Python-list mailing list