wifly tcp echo client example

Dependencies:   WiflyInterface mbed

main.cpp

Committer:
samux
Date:
2012-12-20
Revision:
0:8902d0b79ca8

File content as of revision 0:8902d0b79ca8:

#include "mbed.h"
#include "WiflyInterface.h"

const char* ECHO_SERVER_ADDRESS = "192.168.1.2";
const int ECHO_SERVER_PORT = 7;

/* wifly object where:
*     - p9 and p10 are for the serial communication
*     - p25 is for the reset pin
*     - p26 is for the connection status
*     - "mbed" is the ssid of the network
*     - "password" is the password
*     - WPA is the security
*/
WiflyInterface wifly(p9, p10, p25, p26, "mbed", "password", WPA);

int main() {
    wifly.init(); // use DHCP
    while (!wifly.connect()); // join the network
    printf("IP Address is %s\n\r", wifly.getIPAddress());
    
    TCPSocketConnection socket;
    while (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT) < 0) {
        printf("Unable to connect to (%s) on port (%d)\r\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
        wait(1);
    }
    socket.set_blocking(false, 1500);
    
    char out_buffer[256];
    char in_buffer[256];
    int i = 0;
    
    while (1) {
        sprintf(out_buffer, "Echo TCP client: %d\r\n", i++);
        int len = strlen(out_buffer);
        socket.send_all(out_buffer, len);
    
        int n = socket.receive_all(in_buffer, len);
        if (n < 0) continue;
        
        in_buffer[n] = '\0';
        printf("%s", in_buffer);
    }
}