TCP Echo Client example

Dependencies:   EthernetInterface mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "EthernetInterface.h"
00003 
00004 const char* ECHO_SERVER_ADDRESS = "192.168.2.2";
00005 const int ECHO_SERVER_PORT = 7;
00006 
00007 int main() {
00008     EthernetInterface eth;
00009     eth.init(); //Use DHCP
00010     eth.connect();
00011     printf("\nClient IP Address is %s\n", eth.getIPAddress());
00012     
00013     // Connect to Server
00014     TCPSocketConnection socket;
00015     while (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT) < 0) {
00016         printf("Unable to connect to (%s) on port (%d)\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
00017         wait(1);
00018     }
00019     printf("Connected to Server at %s\n",ECHO_SERVER_ADDRESS);
00020     
00021     // Send message to server
00022     char hello[] = "Hello World";
00023     printf("Sending  message to Server : '%s' \n",hello);
00024     socket.send_all(hello, sizeof(hello) - 1);
00025     
00026     // Receive message from server
00027     char buf[256];
00028     int n = socket.receive(buf, 256);
00029     buf[n] = '\0';
00030     printf("Received message from server: '%s'\n", buf);
00031     
00032     // Clean up
00033     socket.close();
00034     eth.disconnect();
00035     
00036     while(true) {}
00037 }