TCP Server

UiFlow2 Example

echo server

Open the cores3_tcp_server_example.m5f2 project in UiFlow2.

This example creates a TCP server that echoes the received data.

UiFlow2 Code Block:

cores3_tcp_server_example.png

Example output:

None

MicroPython Example

echo server

This example creates a TCP server that echoes the received data.

MicroPython Code Block:

  1# SPDX-FileCopyrightText: 2025 M5Stack Technology CO LTD
  2#
  3# SPDX-License-Identifier: MIT
  4
  5import os, sys, io
  6import M5
  7from M5 import *
  8import network
  9import socket
 10
 11
 12label0 = None
 13label1 = None
 14label2 = None
 15label3 = None
 16label4 = None
 17label5 = None
 18label6 = None
 19label7 = None
 20label8 = None
 21label9 = None
 22title0 = None
 23wlan = None
 24tcps = None
 25
 26
 27con_info = None
 28con_sock = None
 29address = None
 30data = None
 31
 32
 33def setup():
 34    global \
 35        label0, \
 36        label1, \
 37        label2, \
 38        label3, \
 39        label4, \
 40        label5, \
 41        label6, \
 42        label7, \
 43        label8, \
 44        label9, \
 45        title0, \
 46        wlan, \
 47        tcps, \
 48        con_info, \
 49        con_sock, \
 50        address, \
 51        data
 52
 53    M5.begin()
 54    Widgets.fillScreen(0x222222)
 55    label0 = Widgets.Label("Local IP:", 4, 32, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 56    label1 = Widgets.Label("Local Port:", 4, 60, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 57    label2 = Widgets.Label("Remote IP:", 4, 88, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 58    label3 = Widgets.Label("Remote Port:", 4, 118, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 59    label4 = Widgets.Label("Data:", 4, 144, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 60    label5 = Widgets.Label("label5", 136, 32, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 61    label6 = Widgets.Label("label6", 136, 60, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 62    label7 = Widgets.Label("label7", 136, 88, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 63    label8 = Widgets.Label("label8", 136, 118, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 64    label9 = Widgets.Label("label9", 136, 144, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
 65    title0 = Widgets.Title("TCP Server", 3, 0xFFFFFF, 0x0000FF, Widgets.FONTS.DejaVu24)
 66
 67    wlan = network.WLAN(network.STA_IF)
 68    wlan.active(True)
 69    tcps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 70    tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 71    tcps.bind(("0.0.0.0", 8001))
 72    tcps.listen(5)
 73    tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 74    label5.setText(str(wlan.ifconfig()[0]))
 75    label6.setText(str("8001"))
 76
 77
 78def loop():
 79    global \
 80        label0, \
 81        label1, \
 82        label2, \
 83        label3, \
 84        label4, \
 85        label5, \
 86        label6, \
 87        label7, \
 88        label8, \
 89        label9, \
 90        title0, \
 91        wlan, \
 92        tcps, \
 93        con_info, \
 94        con_sock, \
 95        address, \
 96        data
 97    M5.update()
 98    con_info = tcps.accept()
 99    con_sock = con_info[0]
100    address = con_info[1]
101    label7.setText(str(address[0]))
102    label8.setText(str(address[1]))
103    while True:
104        data = con_sock.recv(1024)
105        label9.setText(str(data))
106        con_sock.send(data)
107
108
109if __name__ == "__main__":
110    try:
111        setup()
112        while True:
113            loop()
114    except (Exception, KeyboardInterrupt) as e:
115        try:
116            from utility import print_error_msg
117
118            print_error_msg(e)
119        except ImportError:
120            print("please update to latest firmware")

Example output:

None

API

socket.socket()
socket.bind(address)
socket.listen([backlog])

Create a socket object and bind it to an address.

Parameters:
  • address (tuple) – A tuple containing the server IP address and port number.

  • backlog (int) – The maximum number of queued connections. Default is 5.

Returns:

A socket object.

Return type:

socket.socket

UiFlow2 Code Block:

init.png

MicroPython Code Block:

import socket

tcps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcps.bind(('0.0.0.0', 8001))
tcps.listen(5)
socket.close()

Close the socket connection.

UiFlow2 Code Block:

close.png

close_client.png

MicroPython Code Block:

tcps.close()
socket.accept()

Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

Returns:

A tuple containing the client socket and the address of the client.

Return type:

tuple

UiFlow2 Code Block:

accept.png

MicroPython Code Block:

client_socket, addr = tcps.accept()
print('Connected by', addr)
socket.recv(bufsize)

Receive data from the socket.

Parameters:

bufsize (int) – The maximum amount of data to be received at once.

Returns:

The received data.

Return type:

bytes

UiFlow2 Code Block:

recv.png

MicroPython Code Block:

data = tcps.recv(1024)
print(data)
socket.read()

Read data from the socket.

Returns:

The received data.

Return type:

bytes

UiFlow2 Code Block:

read.png

MicroPython Code Block:

data = tcps.read()
print(data)
socket.send(data)

Send data to the socket. The socket must be connected to a remote socket.

Parameters:

data (bytes | str) – The data to be sent.

Returns:

The number of bytes sent.

Return type:

int

UiFlow2 Code Block:

send.png

MicroPython Code Block:

tcps.send(b'Hello, World!')
tcps.send('Hello, World!')
socket.write(data)

Write the buffer of bytes to the socket. This function will try to write all data to a socket (no “short writes”). This may be not possible with a non-blocking socket though, and returned value will be less than the length of buf.

Parameters:

data (bytes | str) – The data to be sent.

Returns:

The number of bytes sent.

Return type:

int

UiFlow2 Code Block:

write.png

MicroPython Code Block:

tcps.write(b'Hello, World!')
tcps.write('Hello, World!')
socket.setblocking(flag)

Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode.

This method is a shorthand for certain settimeout() calls:

  • sock.setblocking(True) is equivalent to sock.settimeout(None)

  • sock.setblocking(False) is equivalent to sock.settimeout(0)

param bool flag:

If True, the socket will be in blocking mode. If False, the socket will be in non-blocking mode.

return:

None

rtype:

None

UiFlow2 Code Block:

setblocking.png

MicroPython Code Block:

tcps.setblocking(True)
tcps.setblocking(False)
socket.settimeout(timeout)

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise an OSError exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

Parameters:

timeout (float) – The timeout value in seconds. If None, the socket is put in blocking mode.

Returns:

None

Return type:

None

UiFlow2 Code Block:

settimeout.png

MicroPython Code Block:

tcps.settimeout(5)
tcps.settimeout(None)
socket.setsockopt(level, optname, value)

Set the value of the given socket option. The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a bytes-like object representing a buffer.

Parameters:
  • level (int) – The level at which the option is defined.

  • optname (int) – The name of the option to set.

  • value – The value to set for the option.

UiFlow2 Code Block:

setsockopt.png

MicroPython Code Block:

tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 0)
tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)