Init

Dependencies:   mbed WIZnetInterface

Committer:
aiden1536
Date:
Mon Sep 28 07:18:10 2020 +0000
Revision:
0:90e18025a8ed
Init

Who changed what in which revision?

UserRevisionLine numberNew contents of line
aiden1536 0:90e18025a8ed 1 #include "mbed.h"
aiden1536 0:90e18025a8ed 2 #include "EthernetInterface.h"
aiden1536 0:90e18025a8ed 3
aiden1536 0:90e18025a8ed 4 #define ECHO_SERVER_PORT 7
aiden1536 0:90e18025a8ed 5
aiden1536 0:90e18025a8ed 6 int main (void)
aiden1536 0:90e18025a8ed 7 {
aiden1536 0:90e18025a8ed 8 printf("Wait a second...\r\n");
aiden1536 0:90e18025a8ed 9 uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x00, 0x01, 0x02};
aiden1536 0:90e18025a8ed 10 EthernetInterface eth;
aiden1536 0:90e18025a8ed 11 eth.init(mac_addr); //Use DHCP
aiden1536 0:90e18025a8ed 12 eth.connect();
aiden1536 0:90e18025a8ed 13 printf("Server IP Address is %s\r\n", eth.getIPAddress());
aiden1536 0:90e18025a8ed 14
aiden1536 0:90e18025a8ed 15 TCPSocketServer server;
aiden1536 0:90e18025a8ed 16 server.bind(ECHO_SERVER_PORT);
aiden1536 0:90e18025a8ed 17 server.listen();
aiden1536 0:90e18025a8ed 18
aiden1536 0:90e18025a8ed 19 while (true)
aiden1536 0:90e18025a8ed 20 {
aiden1536 0:90e18025a8ed 21 printf("Wait for new connection...\r\n");
aiden1536 0:90e18025a8ed 22 TCPSocketConnection client;
aiden1536 0:90e18025a8ed 23 server.accept(client);
aiden1536 0:90e18025a8ed 24 client.set_blocking(false, 15000); // Timeout after (1.5)s
aiden1536 0:90e18025a8ed 25
aiden1536 0:90e18025a8ed 26 printf("Connection from: %s\r\n", client.get_address());
aiden1536 0:90e18025a8ed 27 char buffer[256];
aiden1536 0:90e18025a8ed 28 while (true) {
aiden1536 0:90e18025a8ed 29 int n = client.receive(buffer, sizeof(buffer));
aiden1536 0:90e18025a8ed 30 if (n <= 0) break;
aiden1536 0:90e18025a8ed 31
aiden1536 0:90e18025a8ed 32 // print received message to terminal
aiden1536 0:90e18025a8ed 33 buffer[n] = '\0';
aiden1536 0:90e18025a8ed 34 printf("Received message from Client :'%s'\r\n",buffer);
aiden1536 0:90e18025a8ed 35
aiden1536 0:90e18025a8ed 36 // reverse the message
aiden1536 0:90e18025a8ed 37 char temp;
aiden1536 0:90e18025a8ed 38 for(int f = 0, l = n-1; f<l; f++,l--){
aiden1536 0:90e18025a8ed 39 temp = buffer[f];
aiden1536 0:90e18025a8ed 40 buffer[f] = buffer[l];
aiden1536 0:90e18025a8ed 41 buffer[l] = temp;
aiden1536 0:90e18025a8ed 42 }
aiden1536 0:90e18025a8ed 43
aiden1536 0:90e18025a8ed 44 // print reversed message to terminal
aiden1536 0:90e18025a8ed 45 printf("Sending message to Client: '%s'\r\n",buffer);
aiden1536 0:90e18025a8ed 46
aiden1536 0:90e18025a8ed 47 // Echo received message back to client
aiden1536 0:90e18025a8ed 48 client.send_all(buffer, n);
aiden1536 0:90e18025a8ed 49 if (n <= 0) break;
aiden1536 0:90e18025a8ed 50 }
aiden1536 0:90e18025a8ed 51
aiden1536 0:90e18025a8ed 52 client.close();
aiden1536 0:90e18025a8ed 53 }
aiden1536 0:90e18025a8ed 54
aiden1536 0:90e18025a8ed 55 }
aiden1536 0:90e18025a8ed 56