Curious Minds

Clear answers to science and history questions

MicroPython Socket Send: How It Works

· 6 min read · Science

In MicroPython, socket send works by copying bytes from your program into the network stack's transmit buffer and returning the number of bytes accepted for sending; it does not guarantee that all the data has left the device or even that the remote peer has received it. The call blocks until at least some data can be queued, and you must check the return value and loop if you need to send a fixed amount.

Background: What a Socket Is in MicroPython

A socket is an endpoint for network communication. In MicroPython, the socket module provides a thin layer over the underlying TCP/IP stack of the port you are running on — for example, the lwIP stack on ESP32 and STM32 ports, or the native stack on Unix and the Windows port. The API deliberately mirrors CPython's socket module so that code can be moved between desktop Python and microcontrollers with minimal changes, but the implementation is smaller and has different buffering behaviour.

When you call socket.socket(socket.AF_INET, socket.SOCK_STREAM) you get a TCP socket. After connect() to a remote address, or after accept() on a listening socket, the socket is ready for send() and recv(). UDP sockets use SOCK_DGRAM and sendto(), which behaves differently because datagrams are sent as whole units.

How send() Works Step by Step

At the API level, sock.send(data) takes a bytes-like object and returns an integer: the number of bytes that the network stack accepted. The sequence inside the stack is roughly:

  1. Your bytes are copied into the socket's send buffer, which is a fixed-size region of RAM managed by the TCP/IP stack.
  2. If the buffer has free space, the copy succeeds and send() returns the number of bytes copied.
  3. If the buffer is full, the call blocks (in blocking mode) until space becomes available, or raises an error (in non-blocking mode).
  4. The stack then segments the buffered data into TCP segments, adds headers, and hands them to the network interface driver.
  5. The driver transmits the segments; TCP retransmits lost segments and waits for acknowledgements from the peer.

The key point is that the return value counts bytes accepted into the buffer, not bytes acknowledged by the remote host. A successful send() of 100 bytes means 100 bytes are now the stack's responsibility; it does not mean the peer's application has read them.

Blocking vs Non-Blocking Sockets

By default, MicroPython sockets are blocking. If the send buffer is full, send() waits. This is simple but can stall your program — for example, a sensor loop that also sends data over Wi-Fi may freeze while the network is congested.

You can call sock.setblocking(False) to make the socket non-blocking. Then send() raises an OSError with an error code such as EAGAIN (11 on many ports) when the buffer is full, instead of waiting. A common pattern is to catch that exception and retry later, or to use select.poll() to wait until the socket is writable before calling send() again.

MicroPython also supports timeouts on some ports via settimeout(), which makes blocking operations raise after a given number of seconds. Availability and exact behaviour vary by port, so check the documentation for your board.

Partial Sends and Why You Must Loop

Because send() may accept fewer bytes than you passed, robust code must loop until all data is sent. A typical helper looks like this:

def send_all(sock, data):
    total = 0
    while total < len(data):
        sent = sock.send(data[total:])
        if sent == 0:
            raise OSError("socket closed")
        total += sent
    return total

Without the loop, a large payload — say a 4 KB JSON message — might be partially sent, leaving the peer with a truncated message and no obvious error on your side. This is one of the most common bugs in MicroPython network code.

Buffer Sizes and Memory Constraints

Microcontrollers have limited RAM, and the TCP send buffer is typically a few kilobytes per socket. On ESP32 and similar chips, the default buffer may be around 2–5 KB depending on configuration. Sending a large block in one call can therefore fill the buffer immediately, causing send() to block or return a partial count.

You can sometimes adjust buffer sizes with setsockopt() using SOL_SOCKET and SO_SNDBUF, but support and maximum values depend on the port. In practice, it is often better to send data in chunks of a few hundred bytes and let the stack manage flow control.

Common Problems and How to Diagnose Them

  • Truncated messages: You ignored the return value of send(). Fix by looping as shown above.
  • Program freezes: A blocking send() is waiting for buffer space because the peer is not reading or the network is down. Use non-blocking mode or a timeout.
  • OSError with EAGAIN: You are in non-blocking mode and the buffer is full. Wait for writability with select before retrying.
  • Connection reset: The peer closed the connection. send() may raise ECONNRESET or return 0. Handle it and close your socket.
  • Data never arrives: Remember that send() only queues data. If the link is lost before transmission, TCP will retransmit for a while, then give up and report an error on a later call.

send() vs sendall() and Other Alternatives

CPython provides sendall(), which loops internally until all data is sent. MicroPython's socket module historically does not include sendall() on all ports, so the manual loop is the portable approach. Some ports may offer it; check your version.

For UDP, sendto() sends a complete datagram in one call and returns the number of bytes sent. Datagrams are not split or merged by the stack, so partial sends are less of an issue, but the maximum datagram size is limited by the MTU (often around 1,400 bytes on Ethernet and Wi-Fi).

Higher-level alternatives include socket.write() on some ports (a stream-oriented method) and the asyncio stream API, which wraps sockets and handles partial writes for you. The urequests library builds HTTP on top of sockets and is convenient for simple requests, though it adds overhead.

Frequently Asked Questions

Does socket.send() guarantee delivery?

No. It only guarantees that the bytes were accepted by the local network stack. TCP will attempt delivery, but the call returns before any acknowledgement from the peer. Delivery confirmation requires an application-level reply or a higher-level protocol.

Why does send() return a smaller number than I passed?

The send buffer had less free space than the size of your data. The stack accepted what fit and returned that count. You must call send() again with the remaining bytes.

Can I send a string directly?

No, send() expects a bytes-like object. Encode strings first, for example sock.send(b"hello") or sock.send("hello".encode()).

What happens if the remote host closes the connection?

A subsequent send() may raise OSError (for example ECONNRESET or EPIPE) or return 0 on some ports. Your code should catch the error and close the socket.

Is send() thread-safe?

MicroPython does not generally support preemptive multithreading, so concurrency is usually cooperative via asyncio or interrupts. Avoid calling send() from an interrupt handler; queue data and send it from the main loop instead.

In this article
  1. Background: What a Socket Is in MicroPython
  2. How send() Works Step by Step
  3. Blocking vs Non-Blocking Sockets
  4. Partial Sends and Why You Must Loop
  5. Buffer Sizes and Memory Constraints
  6. Common Problems and How to Diagnose Them
  7. send() vs sendall() and Other Alternatives
  8. Frequently Asked Questions