30. Chapter TCP/IP
In this chapter, we will introduce how ESP32-S3 implements network communications based on TCP/IP protocol. There are two roles in TCP/IP communication, namely Server and Client, which will be implemented respectively with two projects in this chapter.
30.1. Project As Client
In this section, ESP32-S3 is used as Client to connect Server on the same LAN and communicate with it.
30.1.1. Component List
ESP32-S3 WROOM x1
|
USB cable x1
|
30.1.2. Component knowledge
30.1.2.1. TCP connection
Before transmitting data, TCP needs to establish a logical connection between the sending end and the receiving end. It provides reliable and error-free data transmission between the two computers. In the TCP connection, the client and the server must be clarified. The client sends a connection request to the server, and each time such a request is proposed, a “three-times handshake” is required.
Three-times handshake: In the TCP protocol, during the preparation phase of sending data, the client and the server interact three times to ensure the reliability of the connection, which is called “three-times handshake”.
The first handshake, the client sends a connection request to the server and waits for the server to confirm.
The second handshake, the server sends a response back to the client informing that it has received the connection request.
The third handshake, the client sends a confirmation message to the server again to confirm the connection.
TCP is a connection-oriented, low-level transmission control protocol. After TCP establishes a connection, the client and server can send and receive messages to each other, and the connection will always exist as long as the client or server does not initiate disconnection. Each time one party sends a message, the other party will reply with an ack signal.
30.1.2.2. Install Processing
In this tutorial, we use Processing to build a simple TCP/IP communication platform.
If you’ve not installed Processing, you can download it by clicking https://processing.org/download/. You can choose an appropriate version to download according to your PC system.
Unzip the downloaded file to your computer. Click “processing.exe” as the figure below to run this software.
30.1.2.3. Use Server mode for communication
Install ControlP5.
Open the “ Freenove_Ultimate_Starter_Kit_for_ESP32_S3\Sketches\Sketches\Sketch_31.1_WiFiClient\sketchWiFi\sketchWiFi.pde “, and click “Run”.
The new pop-up interface is as follows. If ESP32-S3 is used as client, select TCP SERVER mode for sketchWiFi.
When sketchWiFi selects TCP SERVER mode, ESP32-S3 Sketch needs to be changed according to sketchWiFi’s displaying of LOCAL IP or LOCAL PORT.
If ESP32-S3 serves as server, select TCP CLIENT mode for sketchWiFi.
When sketchWiFi selects TCP CLIENT mode, the LOCAL IP and LOCAL PORT of sketchWiFi need to be changed according to the IP address and port number printed by the serial monitor.
Mode selection: select Server mode/Client mode.
IP address: In server mode, this option does not need to be filled in, and the computer will automatically obtain the IP address.
In client mode, fill in the remote IP address to be connected.
Port number: In server mode, fill in a port number for client devices to make an access connection.
In client mode, fill in port number given by the Server devices to make an access connection.
Start button: In server mode, push the button, then the computer will serve as server and open a port number for client to make access connection. During this period, the computer will keep monitoring.
In client mode, before pushing the button, please make sure the server is on, remote IP address and remote port number is correct; push the button, and the computer will make access connection to the remote port number of the remote IP as a client.
clear receive: clear out the content in the receiving text box
clear send: clear out the content in the sending text box
Sending button: push the sending button, the computer will send the content in the text box to others.
30.1.3. Circuit
Connect Freenove ESP32-S3 to the computer using the USB cable.
30.1.4. Code
Before running the Code, please open “sketchWiFi.pde.” first, and click “Run”.
The newly pop up window will use the computer’s IP address by default and open a data monitor port. Click“Listening”。
Move the program folder “Freenove_Ultimate_Starter_Kit_for_ESP32_S3/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “TCP_as_Client” and double click “TCP_as_Client.py”.
Before clicking “Run current script”, please modify the name and password of your router and fill in the “host” and “port” according to the IP information shown in the box below:
30.1.4.1. TCP_as_Client
Click “Run current script” and in “Shell”, you can see ESP32-S3 automatically connects to sketchWiFi.
If you don’t click “Listening” for sketchWiFi, ESP32-S3 will fail to connect and will print information as follows:
ESP32-S3 connects with TCP SERVER, and TCP SERVER receives messages from ESP32S3, as shown in the figure below. You can enter any content in TCP SERVER, click SEND, and ESP32-S3 will receive this message
The following is the program code:
1import network
2import socket
3import time
4
5ssidRouter = "********" #Enter the router name
6passwordRouter = "********" #Enter the router password
7host = "192.168.1.139" #input the remote server
8port = 8888 #input the remote port
9
10wlan=None
11s=None
12
13def connectWifi(ssid,passwd):
14 global wlan
15 wlan=network.WLAN(network.STA_IF)
16 wlan.active(True)
17 wlan.disconnect()
18 wlan.connect(ssid,passwd)
19 while(wlan.ifconfig()[0]=='0.0.0.0'):
20 time.sleep(1)
21 return True
22try:
23 connectWifi(ssidRouter,passwordRouter)
24 s = socket.socket()
25 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
26 s.connect((host,port))
27 print("TCP Connected to:", host, ":", port)
28 s.send('Hello')
29 s.send('This is my IP.')
30 while True:
31 data = s.recv(1024)
32 if(len(data) == 0):
33 print("Close socket")
34 s.close()
35 break
36 print(data)
37 ret=s.send(data)
38except:
39 print("TCP close, please reset!")
40 if (s):
41 s.close()
42 wlan.disconnect()
43 wlan.active(False)
Import network、socket、time modules.
1import network
2import socket
3import time
Enter the actual router name, password, remote server IP address, and port number.
1ssidRouter = "********" #Enter the router name
2passwordRouter = "********" #Enter the router password
3host = "192.168.1.139" #input the remote server
4port = 8888 #input the remote port
Connect specified Router until it is successful.
1def connectWifi(ssid,passwd):
2 global wlan
3 wlan=network.WLAN(network.STA_IF)
4 wlan.active(True)
5 wlan.disconnect()
6 wlan.connect(ssid,passwd)
7 while(wlan.ifconfig()[0]=='0.0.0.0'):
8 time.sleep(1)
9 return True
Connect router and then connect it to remote server.
1connectWifi(ssidRouter,passwordRouter)
2s = socket.socket()
3s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4s.connect((host,port))
5print("TCP Connected to:", host, ":", port)
Send messages to the remote server, receive the messages from it and print them out, and then send the messages back to the server.
1s.send('Hello')
2s.send('This is my IP.')
3while True:
4 data = s.recv(1024)
5 if(len(data) == 0):
6 print("Close socket")
7 s.close()
8 break
9 print(data)
10 ret=s.send(data)
If an exception occurs in the program, for example, the remote server is shut down, execute the following program, turn off the socket function, and disconnect the WiFi.
1print("TCP close, please reset!")
2if (s):
3 s.close()
4wlan.disconnect()
5wlan.active(False)
30.1.4.2. Reference
- Class socket
Before each use of socket , please add the statement “ import socket ” to the top of the python file.
socket([af, type, proto]): Create a socket.
af: address
socket.AF_INET: IPv4
socket.AF_INET6: IPv6
type: type
socket.SOCK_STREAM : TCP stream
socket.SOCK_DGRAM : UDP datagram
socket.SOCK_RAW : Original socket
socket.SO_REUSEADDR : socket reusable
proto: protocol number
socket.IPPROTO_TCP: TCPmode
socket.IPPROTO_UDP: UDPmode
socket.setsockopt(level, optname, value): Set the socket according to the options.
Level: Level of socket option
socket.SOL_SOCKET: Level of socket option. By default, it is 4095.
optname: Options of socket
socket.SO_REUSEADDR: Allowing a socket interface to be tied to an address that is already in use.
value: The value can be an integer or a bytes-like object representing a buffer.
socket.connect(address): To connect to server.
Address: Tuple or list of the server’s address and port number
send(bytes): Send data and return the bytes sent.
recv(bufsize): Receive data and return a bytes object representing the data received.
close(): Close socket.
To learn more please visit: http://docs.micropython.org/en/latest/
30.2. Project As Server
In this section, ESP32-S3 is used as a server to wait for the connection and communication of client on the same LAN.
30.2.1. Component List
ESP32-S3 WROOM x1
|
USB cable x1
|
30.2.2. Circuit
Connect Freenove ESP32-S3 to the computer using a USB cable.
30.2.3. Code
Move the program folder “Freenove_Ultimate_Starter_Kit_for_ESP32_S3/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “TCP_as_Server” and double click “TCP_as_Server.py”.
Before clicking “Run current script”, please modify the name and password of your router shown in the box below.
30.2.3.1. TCP_as_Server
After making sure that the router’s name and password are correct, click “Run current script” and in “Shell”, you can see a server opened by the ESP32-S3 waiting to connecting to other network devices.
Processing:
Open the “Freenove_Ultimate_Starter_Kit_for_ESP32_S3/Codes/MicroPython_Codes/TCP_as_Server/sketchWiFi/sketchWiFi.pde”.
Based on the message printed in “Shell”, enter the correct IP address and port when processing, and click to establish a connection with ESP32-S3 to communicate.
You can enter any information in the “Send Box” of sketchWiFi. Click “Send” and ESP32-S3 will print the received messages to “Shell” and send them back to sketchWiFi.
The following is the program code:
1import network
2import socket
3import time
4
5ssidRouter = "********" #Enter the router name
6passwordRouter = "********" #Enter the router password
7port = 8000 #input the remote port
8wlan=None
9listenSocket=None
10
11def connectWifi(ssid,passwd):
12 global wlan
13 wlan=network.WLAN(network.STA_IF)
14 wlan.active(True)
15 wlan.disconnect()
16 wlan.connect(ssid,passwd)
17 while(wlan.ifconfig()[0]=='0.0.0.0'):
18 time.sleep(1)
19 return True
20
21try:
22 connectWifi(ssidRouter,passwordRouter)
23 ip=wlan.ifconfig()[0]
24 listenSocket = socket.socket()
25 listenSocket.bind((ip,port))
26 listenSocket.listen(1)
27 listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
28 print ('tcp waiting...')
29 while True:
30 print("Server IP:",ip,"\tPort:",port)
31 print("accepting.....")
32 conn,addr = listenSocket.accept()
33 print(addr,"connected")
34 break
35 conn.send('I am Server')
36 while True:
37 data = conn.recv(1024)
38 if(len(data) == 0):
39 print("close socket")
40 listenSocket.close()
41 wlan.disconnect()
42 wlan.active(False)
43 break
44 else:
45 print(data)
46 ret = conn.send(data)
47except:
48 print("Close TCP-Server, please reset.")
49 if(listenSocket):
50 listenSocket.close()
51 wlan.disconnect()
52 wlan.active(False)
53
54
Call function connectWifi() to connect to router and obtain the dynamic IP that it assigns to ESP32-S3.
1connectWifi(ssidRouter,passwordRouter)
2ip=wlan.ifconfig()[0]
Open the socket server, bind the server to the dynamic IP, and open a data monitoring port.
1listenSocket = socket.socket()
2listenSocket.bind((ip,port))
3listenSocket.listen(1)
4listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Print the server’s IP address and port, monitor the port and wait for the connection of other network devices.
1while True:
2 print("Server IP:",ip,"\tPort:",port)
3 print("accepting.....")
4 conn,addr = listenSocket.accept()
5 print(addr,"connected")
6 break
Each time receiving data, print them in “Shell” and send them back to the client.
1while True:
2 data = conn.recv(1024)
3 if(len(data) == 0):
4 print("close socket")
5 listenSocket.close()
6 wlan.disconnect()
7 wlan.active(False)
8 break
9 else:
10 print(data)
11 ret = conn.send(data)
If the client is disconnected, close the server and disconnect WiFi.
1except:
2 print("Close TCP-Server, please reset.")
3 if(listenSocket):
4 listenSocket.close()
5 wlan.disconnect()
6 wlan.active(False)

