Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
8 years ago. This question has been closed. Reason: Unclear question
How can I estabilish a TCP/IP communication between client/server using MBED?
I am using this code, but it doesn't even gets the IP Adress.
#include "mbed.h" #include "EthernetInterface.h" #include "NetworkAPI/buffer.hpp" #include "NetworkAPI/select.hpp" #include "NetworkAPI/ip/address.hpp" #include "NetworkAPI/tcp/socket.hpp" using namespace network; #define MAX_CLIENTS 5 int main() { EthernetInterface interface; interface.init(); interface.connect(); printf("IP Address is %s\n\r", interface.getIPAddress()); Select select; tcp::Socket server; tcp::Socket client[MAX_CLIENTS]; tcp::Socket *socket = NULL; int result = 0; int index = 0; network::Buffer buffer(256); std::string message("Hello world!"); // Configure the server socket (assume everty thing works) server.open(); server.bind(8888); server.listen(MAX_CLIENTS); // Add sockets to the select api select.set(&server, Select::Read); for (index = 0; index < MAX_CLIENTS; index++) { select.set(&client[index], Select::Read); } do { // Wait for activity result = select.wait(); if (result < -1) { printf("Failed to select\n\r"); break; } // Get the first socket socket = (tcp::Socket *)select.getReadable(); for (; socket != NULL; socket = (tcp::Socket *)select.getReadable()) { // Check if there was a connection request. if (socket->getHandle() == server.getHandle()) { // Find an unused client for (index = 0; index < MAX_CLIENTS; index++) { if (client[index].getStatus() == network::Socket::Closed) { break; } } // Maximum connections reached if (index == MAX_CLIENTS) { printf("Maximum connections reached\n\r"); continue; } // Accept the client socket->accept(client[index]); printf("Client connected %s:%d\n\r", client[index].getRemoteEndpoint().getAddress().toString().c_str(), client[index].getRemoteEndpoint().getPort()); // Send a nice message to the client client[index].write((void *)message.data(), message.size()); continue; } // It was not the server socket, so it must be a client talking to us. switch (socket->read(buffer)) { case 0: // Remote end disconnected printf("Client disconnected %s:%d\n\r", socket->getRemoteEndpoint().getAddress().toString().c_str(), socket->getRemoteEndpoint().getPort()); // Close socket socket->close(); break; case -1: printf("Error while reading data from socket\n\r"); socket->close(); break; default: printf("Message from %s:%d\n\r", socket->getRemoteEndpoint().getAddress().toString().c_str(), socket->getRemoteEndpoint().getPort()); printf("%s\n\r", (char *)buffer.data()); break; } } } while (server.getStatus() == network::Socket::Listening); }