Mistake on this page?
Report an issue in GitHub or email us

TCPSocket

TCPSocket class hierarchy

The TCPSocket class provides the ability to send a stream of data over TCP. TCPSockets maintain a stateful connection that starts with the connect member function. After successfully connecting to a server, you can use the send and recv member functions to send and receive data (similar to writing or reading from a file).

The constructor takes no parameters. To initialize the socket on a specified NetworkInterface, you must call open method, which takes a NetworkStack pointer.

Server socket

You can also use TCP to listen to incoming connections. To do this:

  1. Bind socket to specific port by calling TCPSocket::bind().
  2. Set socket to listening mode by calling TCPSocket::listen().
  3. Accept incoming connection by calling TCPSocket::accept().

Accepting a new connection returns a pointer to a new Socket object that you can use to communicate with the connected peer. Afterward, call this socket's close() function to shut down the connection and clean up the reserved resources.

Accepting a connection leaves the original socket in listening mode. You can continue to accept new connections until you destroy the listening socket, or call its close() method.

TCPSocket class reference

Public Member Functions
 TCPSocket ()
 Create an uninitialized socket. More...
template<typename S >
 TCPSocket (S *stack)
 Create a socket on a network interface. More...
virtual ~TCPSocket ()
 Destroy a socket. More...
virtual int join_multicast_group (const SocketAddress &address)
 Override multicast functions to return error for TCP. More...
nsapi_error_t connect (const char *host, uint16_t port)
 Connects TCP socket to a remote host. More...
virtual nsapi_error_t connect (const SocketAddress &address)
 Connects TCP socket to a remote host. More...
virtual nsapi_size_or_error_t send (const void *data, nsapi_size_t size)
 Send data over a TCP socket. More...
virtual nsapi_size_or_error_t recv (void *data, nsapi_size_t size)
 Receive data over a TCP socket. More...
virtual nsapi_size_or_error_t sendto (const SocketAddress &address, const void *data, nsapi_size_t size)
 Send data on a socket. More...
virtual nsapi_size_or_error_t recvfrom (SocketAddress *address, void *data, nsapi_size_t size)
 Receive a data from a socket. More...
virtual TCPSocketaccept (nsapi_error_t *error=NULL)
 Accepts a connection on a socket. More...
virtual nsapi_error_t listen (int backlog=1)
 Listen for incoming connections. More...
nsapi_error_t open (NetworkStack *stack)
 Open a network socket on the network stack of the given network interface. More...
virtual nsapi_error_t close ()
 defined(DOXYGEN_ONLY) More...
int leave_multicast_group (const SocketAddress &address)
 Leave an IP multicast group. More...
int get_rtt_estimate_to_address (const SocketAddress &address, uint32_t *rtt_estimate)
 Get estimated round trip time to destination address. More...
int get_stagger_estimate_to_address (const SocketAddress &address, uint16_t data_amount, uint16_t *stagger_min, uint16_t *stagger_max, uint16_t *stagger_rand)
 Get estimated stagger value. More...
nsapi_error_t bind (uint16_t port)
 Bind the socket to a port on which to receive data. More...
nsapi_error_t bind (const char *address, uint16_t port)
 Bind the socket to a specific address and port on which to receive data. More...
virtual nsapi_error_t bind (const SocketAddress &address)
 Bind a specific address to a socket. More...
virtual void set_blocking (bool blocking)
 Set blocking or non-blocking mode of the socket. More...
virtual void set_timeout (int timeout)
 Set timeout on blocking socket operations. More...
virtual nsapi_error_t setsockopt (int level, int optname, const void *optval, unsigned optlen)
 Set socket options. More...
virtual nsapi_error_t getsockopt (int level, int optname, void *optval, unsigned *optlen)
 Get socket options. More...
virtual void sigio (mbed::Callback< void()> func)
 Register a callback on state change of the socket. More...
virtual nsapi_error_t getpeername (SocketAddress *address)
 Get the remote-end peer associated with this socket. More...
void attach (mbed::Callback< void()> func)
 Register a callback on state change of the socket. More...
template<typename T , typename M >
void attach (T *obj, M method)
 Register a callback on state change of the socket. More...

TCPSocket example

Here is a client example of HTTP transaction over TCPSocket:

#include "mbed.h"

// Network interface
NetworkInterface *net;

// Socket demo
int main() {
    int remaining;
    int rcount;
    char *p;
    char *buffer = new char[256];
    nsapi_size_or_error_t result;

    // Bring up the ethernet interface
    printf("Mbed OS Socket example\n");

#ifdef MBED_MAJOR_VERSION
    printf("Mbed OS version: %d.%d.%d\n\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
#endif

    net = NetworkInterface::get_default_instance();

    if (!net) {
        printf("Error! No network inteface found.\n");
        return 0;
    }

    result = net->connect();
    if (result != 0) {
        printf("Error! net->connect() returned: %d\n", result);
        return result;
    }

    // Show the network address
    SocketAddress a;
    net->get_ip_address(&a);
    printf("IP address: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");
    net->get_netmask(&a);
    printf("Netmask: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");
    net->get_gateway(&a);
    printf("Gateway: %s\n", a.get_ip_address() ? a.get_ip_address() : "None");

    // Open a socket on the network interface, and create a TCP connection to ifconfig.io
    TCPSocket socket;
    // Send a simple http request
    char sbuffer[] = "GET / HTTP/1.1\r\nHost: ifconfig.io\r\nConnection: close\r\n\r\n";
    nsapi_size_t size = strlen(sbuffer);

    result = socket.open(net);
    if (result != 0) {
        printf("Error! socket.open() returned: %d\n", result);
    }

    result = net->gethostbyname("ifconfig.io", &a);
    if (result != 0) {
        printf("Error! Could not resolve host ifconfig.io. Result: %d\n", result);
    }
    a.set_port(80);
    result = socket.connect(a);
    if (result != 0) {
        printf("Error! socket.connect() returned: %d\n", result);
        goto DISCONNECT;
    }

    // Loop until whole request sent
    while(size) {
        result = socket.send(sbuffer+result, size);
        if (result < 0) {
            printf("Error! socket.send() returned: %d\n", result);
            goto DISCONNECT;
        }
        size -= result;
        printf("sent %d [%.*s]\n", result, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
    }

    // Receieve an HTTP response and print out the response line
    remaining = 256;
    rcount = 0;
    p = buffer;
    while (remaining > 0 && 0 < (result = socket.recv(p, remaining))) {
        p += result;
        rcount += result;
        remaining -= result;
    }
    if (result < 0) {
        printf("Error! socket.recv() returned: %d\n", result);
        goto DISCONNECT;
    }
	// the HTTP response code
    printf("recv %d [%.*s]\n", rcount, strstr(buffer, "\r\n")-buffer, buffer);

    delete[] buffer;

DISCONNECT:
    // Close the socket to return its memory and bring down the network interface
    socket.close();

    // Bring down the ethernet interface
    net->disconnect();
    printf("Done\n");
}

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.