@@ -156,12 +156,14 @@ def connect(self):
156156 def _recv (self , to_read ):
157157 buf = ''
158158 while to_read > 0 :
159- tmp = self ._socket .recv (to_read )
160- if not tmp :
159+ try :
160+ tmp = self ._socket .recv (to_read )
161+ except socket .error :
161162 raise NetworkError (socket .error (errno .ECONNRESET ,
162163 "Lost connection to server during query" ))
163- to_read -= len (tmp )
164- buf += tmp
164+ else :
165+ to_read -= len (tmp )
166+ buf += tmp
165167 return buf
166168
167169 def _read_response (self ):
@@ -207,13 +209,19 @@ def _opt_reconnect(self):
207209
208210 def check (): # Check that connection is alive
209211 buf = ctypes .create_string_buffer (2 )
210- self ._sys_recv (self ._socket .fileno (), buf , 1 ,
211- socket .MSG_DONTWAIT | socket .MSG_PEEK )
212- if ctypes .get_errno () == errno .EAGAIN :
213- ctypes .set_errno (0 )
214- return errno .EAGAIN
215- return (ctypes .get_errno () if ctypes .get_errno ()
216- else errno .ECONNRESET )
212+ try :
213+ sock_fd = self ._socket .fileno ()
214+ except socket .error as e :
215+ if e .errno == errno .EBADF :
216+ return errno .ECONNRESET
217+ else :
218+ self ._sys_recv (sock_fd , buf , 1 ,
219+ socket .MSG_DONTWAIT | socket .MSG_PEEK )
220+ if ctypes .get_errno () == errno .EAGAIN :
221+ ctypes .set_errno (0 )
222+ return errno .EAGAIN
223+ return (ctypes .get_errno () if ctypes .get_errno ()
224+ else errno .ECONNRESET )
217225
218226 last_errno = check ()
219227 if self .connected and last_errno == errno .EAGAIN :
@@ -226,9 +234,10 @@ def check(): # Check that connection is alive
226234 try :
227235 self .connect_basic ()
228236 except NetworkError as e :
229- last_errno = e .errno
230- if last_errno == 0 :
231- break
237+ pass
238+ else :
239+ if self .connected :
240+ break
232241 warn ("Reconnect attempt %d of %d" %
233242 (attempt , self .reconnect_max_attempts ), NetworkWarning )
234243 if attempt == self .reconnect_max_attempts :
0 commit comments