当前位置:网站首页>[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
2022-04-23 08:04:00 【Pluse Lin】
0. Preface
Recently, I found my classmates to participate in the embedded competition , In order to keep your resume from looking poor , Unfortunately, I'm a computer major , Therefore, most of the work is the development of host computer , Maybe I'll do it, too WIFI modular .
Because I learned something in the process , So I intend to record it in the form of blog , For later browsing , I also hope you can gain something from my blog .
I strive to update on time .
1. Introduction to this task
At present, the demand received is the use of upper computer Web Interface ( The earliest idea was GUI), Receive the data from the lower computer ( Use TCP transmission , The following may be changed to UDP), And then put it into web On the web . So what I need to do is :
1.TCP server The establishment of the ( The upper computer does the server , The lower computer is the client )
2. Web The implementation of the interface
3. TCP server towards web server send data .
Considering my poor programming ability and web Development requirements , So I'm going to use Python Development .
TCP server Use socket Library implementation ,web Interface to use flask Realization , Communication is used requests from TCP server towards web server The specified URL send out POST Request to implement .
I will introduce the details below
2. TCP server The establishment of the
Python in , have access to socket Library build TCP server.
I use socketserver modular , It's also based on socket Of , The advantage of using this module is that it is more convenient to establish TCP server, It even eliminates the binding at the time of creation IP port , call accept The way of blocking .
The method when calling is as follows :
# establish TCP server
def start_TCP(host,port):
myserver=socketserver.ThreadingTCPServer((host,port),MyHandler)
print("You have start server,address is: {}:{}".format(host,port))
# Continuous service
myserver.serve_forever()
We noticed that , In constructing classes ThreadingTCPServer The second parameter is MyHandler, This is a custom class , Inherited socketserver.BaseRequestHandler class , Need to rewrite handle function , As follows :
class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
# receive data , Handle
data=self.request.recv(1024)
try:
data=data.decode("gbk")
except:
# Mainly to prevent coding errors
data="cannot show normally!"
# A little packing
object={
"data":time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+" "+data}
# No data received , No direction web server forward
if not data:
break
else:
# Originally intended to make inter thread communication , Then I thought it was web server, Direct hair post Please
print("Got: {}".format(data))
self.request.send("You have successfully sent data!".encode("ascii"))
with requests.post("http://192.168.71.1:5000/",json=object) as r:
pass
The specific process is :
- call self.requests.recv, receive data , The parameter is the receiving length
- Process the data , You can call self.request.send Send a message back to the client
As for to web server Forwarded content , It will be introduced later .
3. Flask web The establishment of the
flask It's open source web frame , It's very easy to learn , As long as there is a certain web Basics ( Even common sense ) You can learn to .
The specific code is as follows :
from flask import *
import threading
app=Flask(__name__)
# Some global variables
messages=[]
length=0
# The main page
@app.route("/",methods=["GET","POST"])
def index_page():
global messages
# receive TCP server Data sent
data=request.get_json()
# If there's data , Then operate accordingly , Here is to add to the global list
if data is not None:
messages.append(data["data"])
# Apply colours to a drawing template
return render_template("index0.html",messages=messages)
#ajax Will send... To this route post Request polling , Used to update routes asynchronously
@app.route("/get_data",methods=['GET','POST'])
def get_data():
# When new data is added , The front end is required to perform corresponding actions , For example, update route
global length
if(length<len(messages)):
length=len(messages)
return "flash"
return ""
The front-end code is as follows
First of all index0.html, Because it's the learning part , Just put a few data
<html>
<head>
</head>
<body>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="{
{url_for('static', filename = 'js/update.js')}}"></script>
<h2> Historical information </h2>
{% for each in messages %}
<p>{
{each}}</p><br>
{% endfor %}
</body>
</html>
This is relatively simple flask Template writing , There will be no more narration here .
Then there is the use of JavaScript Code . I'm sorry , I am right. js Not familiar with , These codes are also found on the Internet + I changed it myself , Therefore, no specific explanation can be given .
var script=document.createElement("script");
script.type="text/javascript";
script.src="jquery.js";
//ajax polling , Every time 100ms Call the function once , namely ajax request
setInterval(
function(){
$.ajax({
url:"/get_data",
async:true,
type:'post', // Looks like post Talent , I'm confused
timeout:10000,
success:function(data){
if(data=="flash"){
//your operation
window.location.reload();// Refresh route , It can also be other operations
}
},
error:function(xhr,type){
window.alert("error!");
}
})
},100
)
4. TCP server towards web server signal communication
Here's a line , namely requests.post request
And it has been shown earlier
# In this study ,web server Of ip And port is 192.168.71.1:5000
with requests.post("http://192.168.71.1:5000/",json=object) as r:
pass
5. General procedure
The general program is used to start web server and TCP server, Because of two server They are all lasting services , Therefore, starting one in the main process will fall into an endless loop , Cannot start another , So I started the two servers on two threads , And set different port numbers to prevent conflicts .
( In fact, I've been confused here , Because according to my simple knowledge , I think two server There should be two processes , It can be put on two threads. It seems that it can also , Instead, many processes failed …… I'll explore it later )
### index.py
from flask import *
import threading
import socketserver
import time
# web Server part
from app_views import *
#TCP Server part
from lib.MyServer import *
def start_TCP(host,port):
myserver=socketserver.ThreadingTCPServer((host,port),MyHandler)
print("You have start server,address is: {}:{}".format(host,port))
myserver.serve_forever()
def start_flask(host,port):
print("you have start flask server,address is: {}:{}".format(host,port))
app.run(host=host,port=port)
def main():
th1=threading.Thread(target=start_flask,args=("192.168.71.1",5000))
th2=threading.Thread(target=start_TCP,args=("192.168.71.1",5001))
th1.start()
th2.start()
if __name__=="__main__":
main()
6. check before acceptance
Start the above code , Open the network debugging assistant , towards 192,168.71.1:5001 send data , You can see that it has been displayed normally in the front end , It proves that the experiment is successful .
7. What can be improved
- Can you direct me to web server send data ? I can't say , Because the feeling still needs to be established TCP Just connect
- Is there any other way of forwarding ? Variables can be shared between threads , Use semaphores to control the transmission and reception relationship , But it can be troublesome
- The front end updates the data except ajax Is there a better way to poll ? Can we realize real asynchronous communication , Avoid unnecessary loads ?
This article is here , Thank you for watching !
版权声明
本文为[Pluse Lin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230629306636.html
边栏推荐
- Learning records of some shooting ranges: sqli labs, upload labs, XSS
- Zhuang understand's TA notes (VI) < fakeenvreflect & rust, rust effect >
- 第四章 无形资产
- Chapter V investment real estate
- 一文了解系列,对web渗透的常见漏洞总结(持续更新)
- Essays (updated from time to time)
- Dvwa 靶场练习记录
- NIH降血脂指南《your guide to lowering your Cholesterol with TLC》笔记(持续更新中)
- Intranet security attack and defense: a practical guide to penetration testing (6): domain controller security
- SAP Query增强开发介绍
猜你喜欢
Redis -- why is the string length of string emstr the upper limit of 44 bytes?
雲計算技能大賽 -- openstack私有雲環境 第一部分
云计算赛项--2020年赛题基础部分[任务3]
yum源仓库本地搭建的两种方法
[极客大挑战 2019]Havefun1
STO With Billing 跨公司库存转储退货
内网渗透系列:内网隧道之dns2tcp
Houdini terrain and fluid solution (simulated debris flow)
BUUCTF [ACTF2020 新生赛]Include1
Unity C single case mode learning review notes
随机推荐
BUUCTF MISC刷題
爬虫学习笔记,学习爬虫,看本篇就够了
LeetCode 1611. 使整数变为 0 的最少操作次数
Complete learning from scratch, machine learning and deep learning, including theory and code implementation, mainly using scikit and mxnet, and some practices (on kaggle)
linux下mysql数据库备份与恢复(全量+增量)
Research on software security based on NLP (I)
Concours de compétences en informatique en nuage - - première partie de l'environnement cloud privé openstack
Go语学习笔记 - 结构体 | 从零开始Go语言
Internal network security attack and defense: a practical guide to penetration testing (IV): Authority improvement analysis and defense
MySQL -- the secret of lock -- how to lock data
Research on system and software security (5)
Research on system and software security (3)
Houdini > rigid body, rigid body breaking RBD
Export all SVG files in the specified path into pictures in PNG format (thumbnail or original size)
VBA appelle SAP RFC pour réaliser la lecture et l'écriture des données
feign如何集成hystrix
内网渗透系列:内网隧道之icmp_tran
Intranet penetration series: dnscat2 of Intranet tunnel
利用sqlmap注入获取网址管理员账号密码
Unity get real geographic map application terrain notes