![](/media/cache/group/logo_IcAX7cw.png.50x50_q85.png)
tcp example
main.cpp
- Committer:
- minamikawa
- Date:
- 2022-01-19
- Revision:
- 0:4e0f31b64b24
File content as of revision 0:4e0f31b64b24:
#include "mbed.h" //MbedOS 5.15 #include "EthernetInterface.h" #define BUFFSIZE 50 #define PORT 80 DigitalOut led1(LED1); EthernetInterface net; TCPSocket server; TCPSocket* client; SocketAddress clientAddress; char *in_buffer; char *out_buffer; static const char* mbedIP = "192.168.0.32"; //IP static const char* mbedMask = "255.255.255.0"; // Mask static const char* mbedGateway = "192.168.0.0"; //Gateway int main (void){ printf("TCP Echo starting...\n"); int net_stat; //#ifndef ROUTER net.disconnect(); net_stat = net.set_network(mbedIP,mbedMask,mbedGateway); //set ip, mask, gateway to net printf("set IP status: %i\n",net_stat); //#endif net_stat = net.connect(); //connect to network printf("connect status: %i\n",net_stat); SocketAddress ip; //make socket for local ip address net.get_ip_address(&ip); //get a info from net const char *p_ip = ip.get_ip_address(); printf("IP address: %s and Port: %d\n", p_ip ? p_ip : "None" , PORT ); SocketAddress mask; net.get_netmask(&mask); const char *p_mask = mask.get_ip_address(); printf("Netmask: %s\n", p_mask ? p_mask : "None"); SocketAddress gateway; net.get_gateway(&gateway); const char *p_gateway = gateway.get_ip_address(); printf("Gateway: %s\n", p_gateway ? p_gateway : "None"); if(ip){ server.open(&net); //open a network socket using info of net server.bind(PORT); //bind the socket to a port which receive data server.listen(1); //prepare for incoming connections while (1) { printf("Server bound and listening\n"); client = server.accept(); //wait until connection has done client->set_blocking(false); 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) { in_buffer = new char[BUFFSIZE]; int n = client->recv(in_buffer, BUFFSIZE); printf("%d\n", n); if (n == 0) { printf("Client disconnected\n"); b = false; }else if(n == NSAPI_ERROR_WOULD_BLOCK){ //printf("data is not here\n"); }else{ in_buffer[n] = '\0'; printf("Received message from Client :'%s'\n", in_buffer); out_buffer = new char[BUFFSIZE]; n = sprintf(out_buffer,"Echo - %s", in_buffer); printf("Sending echo to client\n"); //client->send(out_buffer, n); led1 =! led1; delete []out_buffer; } led1 =! led1; delete []in_buffer; wait_us(10000); } client->close(); } }else{ printf("No IP\n"); net.disconnect(); printf("Program end\n"); } }