wifly tcp echo client example

Dependencies:   WiflyInterface mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "WiflyInterface.h"
00003 
00004 const char* ECHO_SERVER_ADDRESS = "192.168.1.2";
00005 const int ECHO_SERVER_PORT = 7;
00006 
00007 /* wifly object where:
00008 *     - p9 and p10 are for the serial communication
00009 *     - p25 is for the reset pin
00010 *     - p26 is for the connection status
00011 *     - "mbed" is the ssid of the network
00012 *     - "password" is the password
00013 *     - WPA is the security
00014 */
00015 WiflyInterface wifly(p9, p10, p25, p26, "mbed", "password", WPA);
00016 
00017 int main() {
00018     wifly.init(); // use DHCP
00019     while (!wifly.connect()); // join the network
00020     printf("IP Address is %s\n\r", wifly.getIPAddress());
00021     
00022     TCPSocketConnection socket;
00023     while (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT) < 0) {
00024         printf("Unable to connect to (%s) on port (%d)\r\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
00025         wait(1);
00026     }
00027     socket.set_blocking(false, 1500);
00028     
00029     char out_buffer[256];
00030     char in_buffer[256];
00031     int i = 0;
00032     
00033     while (1) {
00034         sprintf(out_buffer, "Echo TCP client: %d\r\n", i++);
00035         int len = strlen(out_buffer);
00036         socket.send_all(out_buffer, len);
00037     
00038         int n = socket.receive_all(in_buffer, len);
00039         if (n < 0) continue;
00040         
00041         in_buffer[n] = '\0';
00042         printf("%s", in_buffer);
00043     }
00044 }