Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
12 years, 7 months ago.
problem understanding code
First of all this is the entire example:
#include "mbed.h"
#include "EthernetInterface.h"
int main() {
EthernetInterface eth;
eth.init(); //Use DHCP
eth.connect(75000);
printf("IP Address is %s\n", eth.getIPAddress());
TCPSocketConnection sock;
sock.connect("mbed.org", 80); //connect socket to host
char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\n\n";
sock.send_all(http_cmd, sizeof(http_cmd)-1);
char buffer[300];
int ret;
while (true) {
ret = sock.receive(buffer, sizeof(buffer)-1);
if (ret <= 0)
break;
buffer[ret] = '\0';
printf("Received %d chars from server:\n%s\n", ret, buffer);
}
sock.close();
eth.disconnect();
while(1) {}
}
Im trying to understand the code in this examle:
TCPSocketConnection sock;
sock.connect("mbed.org", 80);
this means: the mbed makes a socket connected to his own port nr 80??? and makes a connection to the mbed.org website???
char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\n\n";
this means i put in char http_cmd[] what i get from connecting to the mbed.org/media/.....???
sock.send_all(http_cmd, sizeof(http_cmd)-1);
this means when someone askes data from the mbed server i send whats in http_cmd???
char buffer[300];
int ret;
while (true) {
ret = sock.receive(buffer, sizeof(buffer)-1);
if (ret <= 0)
break;
buffer[ret] = '\0';
printf("Received %d chars from server:\n%s\n", ret, buffer);
}
i dont understand what this does, in hyperterminal i get a lot of information about the server and the connection. but how does sock.receive works???
and most important how do i add event handlers to this program? thnx in advance!
1 Answer
12 years, 7 months ago.
This is what basically happens:
mbed opens a socket to website ''mbed.org". The socket uses port 80, that is the port for http (=browser) traffic. mbed then sends a http "GET" command to that socket to ask for file "/media/uploads/mbed_official/hello.txt". mbed then receives that file from the mbed.org website and prints it in your terminal. You get the text in that file (Hello world!) and some info about the server.