Permalink
Browse files

Handle disconnects better in runloop_once

  • Loading branch information...
haakonnessjoen committed May 7, 2014
1 parent 735ce5d commit 66887fa4088c69195ad577387e985cf23682453b
Showing with 20 additions and 0 deletions.
  1. +20 −0 librouteros.c
View
@@ -42,6 +42,14 @@ static int debug = 0;
#ifdef _WIN32
#define snprintf _snprintf
+static int is_connected (SOCKET socket) {
+ char data;
+ int len = recv(socket, &data, 1, MSG_PEEK);
+ if (len < 0) {
+ return WSAGetLastError() == WSAEWOULDBLOCK ? 1 : 0;
+ }
+ return len > 0 ? 1 : 0;
+}
static int _read (SOCKET socket, char *data, int len) {
int rlen = recv(socket, data, len, 0);
if (rlen == SOCKET_ERROR) return -1;
@@ -53,6 +61,14 @@ static int _write(SOCKET socket, char *data, int len) {
return wlen;
}
#else
+static int is_connected (int socket) {
+ char data;
+ int len = recv(socket, &data, 1, MSG_PEEK);
+ if (len < 0) {
+ return errno == EWOULDBLOCK ? 1 : 0;
+ }
+ return len > 0 ? 1 : 0;
+}
#define _read(s,d,l) read(s,d,l)
#define _write(s,d,l) write(s,d,l)
#endif
@@ -234,6 +250,10 @@ int ros_runloop_once(struct ros_connection *conn, void (*callback)(struct ros_re
ros_set_type(conn, ROS_EVENT);
}
+ if (!is_connected(conn->socket)) {
+ return 0;
+ }
+
if (conn->expected_length == 0) {
conn->expected_length = readLen(conn);
if (conn->expected_length > 0) {

0 comments on commit 66887fa

Please sign in to comment.