Example for TCPSocket as EchoServer

main.cpp

Committer:
JohnnyK
Date:
6 months ago
Revision:
0:633c10a3bb5d
Child:
1:8c10d8f4e3aa

File content as of revision 0:633c10a3bb5d:

#include "mbed.h" //MbedOS 5.15
#include "EthernetInterface.h" 
 
#define ROUTER // commented = Static IP uncomented = address assigned by router
#ifndef ROUTER
    #define IP          "192.168.1.1"   //Here place your static IP of Mbed
    #define GATEWAY     "0.0.0.0"
    #define MASK        "255.255.255.0"
#endif
#define PORT            20

DigitalOut led1(LED1);

EthernetInterface eth;
TCPSocket server;
TCPSocket* client;
SocketAddress clientAddress;
 
int main (void){
    printf("TCP Echo starting...\n");
    int eth_stat;
#ifndef ROUTER
    eth.disconnect();
    eth_stat = eth.set_network((SocketAddress)IP,(SocketAddress)MASK,(SocketAddress)GATEWAY);
    printf("set IP status: %i\n",eth_stat);
#endif
    eth_stat = eth.connect();
    printf("connect status: %i\n",eth_stat);

    SocketAddress ip; 
    eth.get_ip_address(&ip);
    const char *p_ip = ip.get_ip_address();
    printf("IP address: %s and Port: %d\n", p_ip ? p_ip : "None" , PORT );
    SocketAddress mask;
    eth.get_netmask(&mask);
    const char *p_mask = mask.get_ip_address();
    printf("Netmask: %s\n", p_mask ? p_mask : "None");
    SocketAddress gateway;
    eth.get_gateway(&gateway);
    const char *p_gateway = gateway.get_ip_address();
    printf("Gateway: %s\n", p_gateway ? p_gateway : "None");
    
    if(ip){ 
        server.open(&eth);
        server.bind(PORT);
        server.listen(1);
        while (1) {
            printf("Server bound and listening\n");
            client = server.accept();

            client->getpeername(&clientAddress);
            const char *p_clientAddress = clientAddress.get_ip_address();
            printf("Client connected from IP address: %s\n", p_clientAddress ? p_clientAddress : "None");
            
            bool b = true;
            while (b) {
                char in_buffer[100];
                int n = client->recv(in_buffer, sizeof(in_buffer));
                if (n == 0) {
                    printf("Client disconnected\n");
                    b = false;
                }else{
                    printf("Received message from Client :'%s'\n", in_buffer);
                    char out_buffer[100];
                    n = sprintf(out_buffer,"Echo - %s", in_buffer);
                    
                    printf("Sending echo to client\n");
                    client->send(out_buffer, n);
                    led1 =! led1;
                }
                led1 =! led1;
            }
            client->close();
        }
    }else{
            printf("No IP\n");
            eth.disconnect();
            printf("Program end\n");
    }
}