In this lesson, we will learn json communication. In the example of this lesson, two sample programs are provided: server.py and client.py, which are on different devices in the same LAN. It can also be run on the same device. Run server.py first and then client.py. Server.py can send two arrays to client.py in a loop, and client.py can be used like a normal array. It is possible to send the dictionary without sending the array, and the method is the same.
25.1 Learning the code program of server.py
Here we use Subline IDE to view and edit the code program of this course. For the specific method, please see "2.4 Editing the Code Program in Raspberry Pi" in Lesson 2.
In the file manager of the MobaXterm terminal, find adeept_rasparms/CourseCode/11Json, and open the code of this lesson: server.py. The specific code and comments are as follows:
Import libraries related to TCP communication.
Initialize the TCP server.
Establish a TCP server and monitor client connections.
Client connection is successful.
Define two arrays.
Encode array into json string.
Send this string.
25.2 Learning the code program of client.py
Here we use Subline IDE to view and edit the code program of this course. For the specific method, please see "2.4 Editing the Code Program in Raspberry Pi" in Lesson 2.
In the file manager of the MobaXterm terminal, find adeept_rasparms/CourseCode/11Json, and open the code of this lesson: client.py. The specific code and comments are as follows:
The IP address here needs to be changed to the IP address of the server, which is the IP address of the device where you run the client.py program. For example, if you run client.py on your computer, then you need to modify SERVER_IP to your computer's IP.
The IP address here needs to be changed to the IP address of the server.
Receive the Json string sent from the server.
Decode the Json string into the corresponding format.
Print output, actually output can now be used as an array.
25.3 How to realize json communication
1. In the file manager of the MobaXterm terminal, find adeept_rasparms/CourseCode/11Json, download the client.py file to your PC, select this folder, click the button to download the file to the PC, and save it in English letters Under the path.
2. In the MobaXterm terminal, log in to your Raspberry Pi and use the command to enter under the adeept_rasparms/CourseCode/11Json:
cd adeept_rasparms/CourseCode/11Json
3.Enter the command to view the contents of the current directory:
ls
4. Enter the command to run the server.py program:
sudo python3 server.py
5.Open the client.py program you downloaded in step 1 on the PC, and then the following data will appear.