![](/media/cache/profiles/af7fc8485f40dc495bc626d6dbe7faf1.50x50_q85.png)
TCP Echo Client example
Dependencies: EthernetInterface mbed-rtos mbed
main.cpp@10:0468b439a484, 2017-02-14 (annotated)
- Committer:
- mbed_official
- Date:
- Tue Feb 14 16:37:18 2017 +0000
- Revision:
- 10:0468b439a484
- Parent:
- 9:a640b18e5931
Update libraries
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
mbed_official | 0:e8f884c94549 | 1 | #include "mbed.h" |
emilmont | 1:a51d8ed156e6 | 2 | #include "EthernetInterface.h" |
emilmont | 1:a51d8ed156e6 | 3 | |
mbedAustin | 9:a640b18e5931 | 4 | const char* ECHO_SERVER_ADDRESS = "192.168.2.2"; |
emilmont | 3:3fbf0efec25a | 5 | const int ECHO_SERVER_PORT = 7; |
emilmont | 1:a51d8ed156e6 | 6 | |
emilmont | 1:a51d8ed156e6 | 7 | int main() { |
emilmont | 1:a51d8ed156e6 | 8 | EthernetInterface eth; |
emilmont | 1:a51d8ed156e6 | 9 | eth.init(); //Use DHCP |
emilmont | 1:a51d8ed156e6 | 10 | eth.connect(); |
mbedAustin | 9:a640b18e5931 | 11 | printf("\nClient IP Address is %s\n", eth.getIPAddress()); |
emilmont | 1:a51d8ed156e6 | 12 | |
mbedAustin | 9:a640b18e5931 | 13 | // Connect to Server |
emilmont | 3:3fbf0efec25a | 14 | TCPSocketConnection socket; |
emilmont | 3:3fbf0efec25a | 15 | while (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT) < 0) { |
emilmont | 3:3fbf0efec25a | 16 | printf("Unable to connect to (%s) on port (%d)\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT); |
emilmont | 1:a51d8ed156e6 | 17 | wait(1); |
emilmont | 1:a51d8ed156e6 | 18 | } |
mbedAustin | 9:a640b18e5931 | 19 | printf("Connected to Server at %s\n",ECHO_SERVER_ADDRESS); |
emilmont | 1:a51d8ed156e6 | 20 | |
mbedAustin | 9:a640b18e5931 | 21 | // Send message to server |
mbedAustin | 9:a640b18e5931 | 22 | char hello[] = "Hello World"; |
mbedAustin | 9:a640b18e5931 | 23 | printf("Sending message to Server : '%s' \n",hello); |
emilmont | 3:3fbf0efec25a | 24 | socket.send_all(hello, sizeof(hello) - 1); |
emilmont | 1:a51d8ed156e6 | 25 | |
mbedAustin | 9:a640b18e5931 | 26 | // Receive message from server |
emilmont | 1:a51d8ed156e6 | 27 | char buf[256]; |
emilmont | 3:3fbf0efec25a | 28 | int n = socket.receive(buf, 256); |
emilmont | 2:563aa530f0dd | 29 | buf[n] = '\0'; |
mbedAustin | 9:a640b18e5931 | 30 | printf("Received message from server: '%s'\n", buf); |
emilmont | 1:a51d8ed156e6 | 31 | |
mbedAustin | 9:a640b18e5931 | 32 | // Clean up |
emilmont | 3:3fbf0efec25a | 33 | socket.close(); |
emilmont | 1:a51d8ed156e6 | 34 | eth.disconnect(); |
emilmont | 1:a51d8ed156e6 | 35 | |
emilmont | 1:a51d8ed156e6 | 36 | while(true) {} |
emilmont | 1:a51d8ed156e6 | 37 | } |