Skip to content
This repository was archived by the owner on Jun 8, 2021. It is now read-only.

Commit 963aa41

Browse files
DeepikaBartek Szatkowski
Deepika
authored and
Bartek Szatkowski
committed
Added error handling for socket:connect,recv and send calls
1 parent e437902 commit 963aa41

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

main.cpp

+21-5
Original file line numberDiff line numberDiff line change
@@ -81,22 +81,38 @@ void scan_demo(WiFiInterface *wifi)
8181
void http_demo(NetworkInterface *net)
8282
{
8383
TCPSocket socket;
84+
nsapi_error_t response;
8485

8586
printf("Sending HTTP request to www.arm.com...\r\n");
8687

8788
// Open a socket on the network interface, and create a TCP connection to www.arm.com
8889
socket.open(net);
89-
socket.connect("www.arm.com", 80);
90+
response = socket.connect("www.arm.com", 80);
91+
if(0 != response) {
92+
printf("Error connecting: %d\r\n", response);
93+
socket.close();
94+
return;
95+
}
9096

9197
// Send a simple http request
9298
char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n";
93-
int scount = socket.send(sbuffer, sizeof sbuffer);
94-
printf("sent %d [%.*s]\r\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
99+
response = socket.send(sbuffer, sizeof sbuffer);
100+
if(response < 0) {
101+
printf("Error sending data: %d\r\n", response);
102+
socket.close();
103+
return;
104+
} else {
105+
printf("sent %d [%.*s]\r\n", response, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
106+
}
95107

96108
// Recieve a simple http response and print out the response line
97109
char rbuffer[64];
98-
int rcount = socket.recv(rbuffer, sizeof rbuffer);
99-
printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
110+
response = socket.recv(rbuffer, sizeof rbuffer);
111+
if(response < 0) {
112+
printf("Error receiving data: %d\r\n", response);
113+
} else {
114+
printf("recv %d [%.*s]\r\n", response, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
115+
}
100116

101117
// Close the socket to return its memory and bring down the network interface
102118
socket.close();

0 commit comments

Comments
 (0)