@@ -202,38 +202,56 @@ void WiFiClient::stop()
202
202
}
203
203
204
204
int WiFiClient::connect (IPAddress ip, uint16_t port)
205
+ {
206
+ return connect (ip,port,-1 );
207
+ }
208
+ int WiFiClient::connect (IPAddress ip, uint16_t port, int32_t timeout)
205
209
{
206
210
int sockfd = socket (AF_INET, SOCK_STREAM, 0 );
207
211
if (sockfd < 0 ) {
208
212
log_e (" socket: %d" , errno);
209
213
return 0 ;
210
214
}
215
+ fcntl ( sockfd, F_SETFL, fcntl ( sockfd, F_GETFL, 0 ) | O_NONBLOCK );
211
216
212
217
uint32_t ip_addr = ip;
213
218
struct sockaddr_in serveraddr;
214
219
bzero ((char *) &serveraddr, sizeof (serveraddr));
215
220
serveraddr.sin_family = AF_INET;
216
221
bcopy ((const void *)(&ip_addr), (void *)&serveraddr.sin_addr .s_addr , 4 );
217
222
serveraddr.sin_port = htons (port);
218
- int res = lwip_connect_r (sockfd, (struct sockaddr *)&serveraddr, sizeof (serveraddr));
219
- if (res < 0 ) {
220
- log_e (" lwip_connect_r: %d" , errno);
223
+ fd_set fdset;
224
+ struct timeval tv;
225
+ FD_ZERO (&fdset);
226
+ FD_SET (sockfd, &fdset);
227
+ tv.tv_sec = 0 ;
228
+ tv.tv_usec = timeout * 1000 ;
229
+ lwip_connect_r (sockfd, (struct sockaddr *)&serveraddr, sizeof (serveraddr));
230
+ int res = select (sockfd + 1 , nullptr , &fdset, nullptr , timeout<0 ? nullptr : &tv);
231
+ if (res != 1 )
232
+ {
233
+ log_e (" select: %d" ,errno);
221
234
close (sockfd);
222
235
return 0 ;
223
236
}
237
+ fcntl ( sockfd, F_SETFL, fcntl ( sockfd, F_GETFL, 0 ) & (~O_NONBLOCK) );
224
238
clientSocketHandle.reset (new WiFiClientSocketHandle (sockfd));
225
239
_rxBuffer.reset (new WiFiClientRxBuffer (sockfd));
226
240
_connected = true ;
227
241
return 1 ;
228
242
}
229
243
230
244
int WiFiClient::connect (const char *host, uint16_t port)
245
+ {
246
+ return connect (host,port,-1 );
247
+ }
248
+ int WiFiClient::connect (const char *host, uint16_t port, int32_t timeout)
231
249
{
232
250
IPAddress srv ((uint32_t )0 );
233
251
if (!WiFiGenericClass::hostByName (host, srv)){
234
252
return 0 ;
235
253
}
236
- return connect (srv, port);
254
+ return connect (srv, port, timeout );
237
255
}
238
256
239
257
int WiFiClient::setSocketOption (int option, char * value, size_t len)
0 commit comments