Chapter 29 TCP/IP
In this chapter, we will introduce how ESP8266 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.
Project 13.1 As Client
In this section, ESP8266 is used as Client to connect Server on the same LAN and communicate with it.
Component List
ESP8266 x1 |
USB cable |
|
|
Component knowledge
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.
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.
Use Server mode for communication
Open the “Freenove_Ultimate_Starter_Kit_for_ESP8266\C\Sketches\Sketch_13.1_WiFiClient\sketchWiFisketchWiFi.pde”, and click “Run”.
The new pop-up interface is as follows. If ESP8266 is used as client, select TCP SERVER mode for sketchWiFi.
When sketchWiFi selects TCP SERVER mode, ESP8266 Sketch needs to be changed according to sketchWiFi’s displaying of LOCAL IP or LOCAL PORT.
If ESP8266 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.
Circuit
Connect Freenove ESP8266 to the computer using USB cable.
Code
If you have not installed “ControlP5”, please follow the following steps to continue the installation, if you have installed, please skip this section.
Open Processing.
Click Add Tool under Tools.
Select Libraries in the pop-up window.
Input “ControlP5” in the searching box, and then select the option as below. Click “Install” and wait for the installation to finish.
You can also click Add Library under ‘Import Library’ under ‘Sketch’.
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_ESP8266/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “13.1_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 in processing app shown in the box below:
13.1_TCP_as_Client
Click “Run current script” and in “Shell”, you can see ESP8266 automatically connects to sketchWiFi.
If you don’t click “Listening” for sketchWiFi, ESP8266 will fail to connect and will print information as follows:
ESP8266 connects with TCP SERVER, and TCP SERVER receives messages from ESP8266, as shown in the figure below.
The following is the program code:
1import network
2import socket
3import time
4
5ssidRouter = "********" #Enter the router name
6passwordRouter = "********" #Enter the router password
7host = "********" #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 = "********" #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)
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/
Project 29.2 As Server
In this section, ESP8266 is used as a server to wait for the connection and communication of client on the same LAN.
Component List
ESP8266 x1 |
USB cable |
|---|---|
|
|
Circuit
Connect Freenove ESP8266 to the computer using USB cable.
Code
Move the program folder “Freenove_Ultimate_Starter_Kit_for_ESP8266/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “29.2_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.
29.2_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 ESP8266 waiting to connecting to other network devices.
Processing:
Open the “ Freenove_Ultimate_Starter_Kit_for_ESP8266/Codes/MicroPython_Codes/29.2_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 ESP8266 to communicate.
You can enter any information in the “Send Box” of sketchWiFi. Click “Send” and ESP8266 will print the received messages to “Shell” and send them back to sketchWiFi.
The following is the program code:
Call function connectWifi() to connect to router and obtain the dynamic IP that it assigns to ESP8266.
Open the socket server, bind the server to the dynamic IP, and open a data monitoring port.
Print the server’s IP address and port, monitor the port and wait for the connection of other network devices.
Each time receiving data, print them in “Shell” and send them back to the client.
If the client is disconnected, close the server and disconnect WiFi.

